jQuery .append(), prepend(), after() ...重复的元素和内容? [英] jQuery .append(), prepend(), after() ... duplicate elements and contents?
本文介绍了jQuery .append(), prepend(), after() ...重复的元素和内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的代码中,这个命令只运行一次:
In my code this command is run only once:
jQuery("#commentrating").append('A');
但是在 div #commentrating
里面出现了两个A"元素!什么可能导致此错误?
but inside the div #commentrating
there appears two "A" elements! What may be causing this bug?
附言.after()
也有问题 :S
推荐答案
可能是事件冒泡引起的.(只是猜测,只要没有进一步的信息)
Maybe it's caused by event-bubbling.(just a guess as long as no further info is available)
假设:
<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>
如果你点击文本,点击会触发内部div并冒泡到外部div,该函数将执行2次.
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.
为了避免这种情况,请使用 stopPropagation()
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>
这篇关于jQuery .append(), prepend(), after() ...重复的元素和内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文