jQuery .append(), prepend(), after() … duplicate elements and contents?

為{幸葍}努か 提交于 2019-11-29 15:27:11

Maybe it's caused by event-bubbling.(just a guess as long as no further info is available)

Assuming this:

<script  type="text/javascript">
jQuery(
  function($)
  {
    $('div')
      .click(function(e)
             {
              $('span',this).append('A');
             }
            );
  }
);
</script>
<div><div><b>click here:</b><span></span></div></div>

if you click on the text, the click will trigger on the inner div and bubble up to the outer div, the function will be executed 2 times.

To avoid this use stopPropagation()

<script  type="text/javascript">
jQuery(
  function($)
  {
    $('div')
      .click(function(e)
             {
              e.stopPropagation();
              $('span',this).append('A');
             }
            );
  }
);
</script>
<div><div><b>click here:</b><span></span></div></div>

Two possible causes:

(when using append, appendTo, prepend, prependTo ...):


1) If you attach 2 source elements to 1 destination element, if you use:

$("destination").append("source");

jQuery somewhere in your html finds 2 source_div elements and appends both of them.

2) If you attach 1 source element to 2 destination, like:

$("destination").append("source");

probably in your html you have 2 destination elements:

<div>
    <div class="destination"></div>
    ......
    <div class="destination"></div>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!