Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jquery:在动态添加的html上使用e.stopPropagation()不起作用_Jquery_Events - Fatal编程技术网

jquery:在动态添加的html上使用e.stopPropagation()不起作用

jquery:在动态添加的html上使用e.stopPropagation()不起作用,jquery,events,Jquery,Events,我有一个html标签,我用点击事件来命名它。 在此之后,我将通过jquery动态添加另一个标记(span)。 我希望span不会执行警报,如何执行? (如果我点击“我是新文本”-我不希望任何事情发生) 您可以在此处进行测试: 我在这里所做的工作不起作用: <b onclick="alert('q1')" id="q1" class="test">test</b> <br> <b onclick="alert('q2')" id="q2" class="t

我有一个html标签,我用点击事件来命名它。
在此之后,我将通过jquery动态添加另一个标记(span)。
我希望span不会执行警报,如何执行?
(如果我点击“我是新文本”-我不希望任何事情发生
您可以在此处进行测试:
我在这里所做的工作不起作用:

<b onclick="alert('q1')" id="q1" class="test">test</b>
<br>
<b onclick="alert('q2')" id="q2" class="test">test</b>
<br>
<b onclick="alert('q3')" id="q3" class="test">test</b>

$(document).ready(function () {
    $(".test").each(function () {
        $(this).append(function () {
            return $('<span id="newChild_'+$(this).attr('id')+'" style="color:red"> I am new Text</div>');
        });
        $('#newChild_' + $(this).attr('id')).live('click', function (e) {
            e.stopPropagation();
        });

    });
});
测试

测试
测试 $(文档).ready(函数(){ $(“.test”)。每个(函数(){ $(this).append(函数(){ return$(“我是新文本”); }); $('#newChild'+$(this.attr('id')).live('click',函数(e){ e、 停止传播(); }); }); });
Live向文档中添加一个侦听器,并检查其中注册的任何事件是否与您输入的选择器匹配。但是onclick位于元素本身,因此它在clicklistener之前执行。 (这也记录在jQuery的live页面上)

顺便说一句,在jQuery1.4中,最好使用委托。

尝试以下方法:

$(document).ready(function () {
    $(".test").each(function () {
        $(this).append( $('<span id="newChild_'+$(this).attr('id')+'" style="color:red"> I am new Text</div>').bind('click', function (e) {
            e.stopPropagation();
        }) );
    });
});
$(文档).ready(函数(){
$(“.test”)。每个(函数(){
$(this).append($('I am new Text').bind('click',函数(e){
e、 停止传播();
}) );
});
});

live
在文档体对象上使用事件冒泡机制和附加的事件处理程序。即使您尝试在
live
处理程序中停止事件传播,它也不会工作,因为就在事件目标之后有
b
标记正在侦听此事件。动态添加标记后,可以尝试使用
bind

看看这个工作原理

$(文档).ready(函数(){
$(“.test”)。每个(函数(){
$(this).append(函数(){
return$(“我是新文本”);
});
$('#newChild'+$(this.attr('id')).bind('click',函数(e){
e、 停止传播();
});
});
});
$(document).ready(function () {
    $(".test").each(function () {
        $(this).append(function () {
            return $('<span id="newChild_'+$(this).attr('id')+'" style="color:red"> I am new Text</div>');
        });
        $('#newChild_' + $(this).attr('id')).bind('click', function (e) {
            e.stopPropagation();
        });

    });
});