开发者

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

In my code this command is run only once:

开发者_StackOverflow中文版
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


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜