如何通过jquery附加嵌套的div?

问题描述 投票:0回答:2

我在幻灯片中有下面的部分代码:

<div id="st_swiper_block_55">
<img class="st_swiper_image" src="https://dev.g2kala.com/upload/stswiper/1slide.jpg" alt=""width="2000" height="750">  
 </div>

并且我想通过jQuery在img标签后添加嵌套潜水:

<div class="hot-spot" x="300" y="43">
            <div class="circle"></div>
            <div class="tooltip">
                <div class="img-row">
                    <img src="https://picsum.photos/170/128/?random">
                </div>
            </div>
</div>

我尝试但不起作用:

  $(document).ready(function() {
var divnested = '<div class="hot-spot" x="300" y="43">';
divnested += '<div class="circle"></div>';
divnested += '<div class="tooltip">';
divnested + ' <div class="img-row">';
divnested + ' <img src="https://picsum.photos/170/128/?random" alt="Jurong Lake Gardens #1"  width="170" height="128">';
divnested + ' </div>';
divnested + '</div>';
divnested + '</div>';
$("#st_swiper_block_55").append($('divnested'));
 });
html jquery css append
2个回答
0
投票

[$('divnested')正在DOM中寻找标签<divnested></divnested>,但它不存在

只需将字符串附加为变量

$("#st_swiper_block_55").append(divnested);

0
投票

问题是因为您要在要附加的jQuery对象中提供选择符字符串,而不是divnested变量。试试这个:

$(document).ready(function() {
  var divnested = '<div class="hot-spot" x="300" y="43"><div class="circle"></div><div class="tooltip"><div class="img-row"><img src="https://picsum.photos/170/128/?random" alt="Jurong Lake Gardens #1"  width="170" height="128"></div></div></div>';
  $("#st_swiper_block_55").append(divnested);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="st_swiper_block_55">
  <img class="st_swiper_image" src="https://dev.g2kala.com/upload/stswiper/1slide.jpg" alt="" width="2000" height="750">
</div>

作为旁注,请小心将自己的非标准属性添加到HTML元素;在这种情况下为xy。如果要将元数据应用于元素,请使用data属性。

© www.soinside.com 2019 - 2024. All rights reserved.