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

好久不见. 提交于 2019-12-18 09:00:20

问题


In my code this command is run only once:

jQuery("#commentrating").append('A');

but inside the div #commentrating there appears two "A" elements! What may be causing this bug?

P.S. .after() is buggy as well :S


回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/7249518/jquery-append-prepend-after-duplicate-elements-and-contents

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