jQuery 使用 $.get() 时阻止点击事件冒泡
我已将单击事件分配给按钮,该按钮检索不同的 HTML 代码段并使用 .html(string) 方法将其注入到 DIV 元素中。
$('#btnClose').click(function(){
$.get('Content.html',function(data) {
$('#EditCategory').html(data);
});
});
Content.html 页面如下:
<button id="btnNewCategory" type="button">Add new category</button>
<script type="text/javascript">
$('#btnNewCategory').click(alert('Test'));
</script>
每次单击“#btnClose”按钮时,都会显示 HTML 片段内容,但也会触发警报(“Test”)。我尝试过 stopPropagation(),preventDefault() 并返回 false;并且没有喜乐。谁能阐明我做错了什么???
I have assigned a click event to a button, which retrieves a different HTML snippet and injects it into a DIV element using the .html(string) method.
$('#btnClose').click(function(){
$.get('Content.html',function(data) {
$('#EditCategory').html(data);
});
});
The Content.html page is as follows:
<button id="btnNewCategory" type="button">Add new category</button>
<script type="text/javascript">
$('#btnNewCategory').click(alert('Test'));
</script>
Every time I click the '#btnClose' button the HTML snipper content is displayed but the alert('Test') is also fired. I've tried stopPropagation(),preventDefault() and return false; and have had no joy. Can anyone shed any light on what I'm doing wrong???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的处理程序应该如下所示:
您当前所拥有的是立即触发
alert('Test')
并尝试将结果分配给点击处理程序(如果您需要)要在单击时运行,请使用像我上面那样的匿名函数。这不是传播问题,请阅读此处以更好地理解,但是具有约束力的:)
Your handler should be like this instead:
What you currently have is firing
alert('Test')
immediately and trying to assign the result to a click handler, if you want it to run when clicked, use an anonymous function like I have above.This isn't a propagation issue, read here for a better understanding of that, but a binding one :)