javascript 追加后jquery事件不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16462052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:45:03  来源:igfitidea点击:

jquery event not working after append

javascriptjquery

提问by shashank

http://jsfiddle.net/YsnhT/2/

http://jsfiddle.net/YsnhT/2/

Jquery event on is not working after the append. I need the value of textarea after I click save button.

Jquery 事件在追加后不起作用。单击保存按钮后,我需要 textarea 的值。

$('.span8')
    .on('click',
            '.btn',
            function() {
        var input = $("#textarea").val();
        alert(input);
    });

$('body').on('click','#createNote',function() {                $('.span8').empty();
                $('.span8').append('<button type="button" class="btn" style="float: right; margin-right: 8px;background-color:#dddddd;font-family:Roboto Slab;color: black" id="save" data-loading-text="Saving...">Save</button><div class="hero-unit"><input type="text" style="width: 100%" id="title" placeholder="Title"/>'+ 
                '<textarea contenteditable="true" id="textarea" class="textarea" placeholder="Enter text ..."style="width: 100%;">dd</textarea></div>');

            });

HTML:

HTML:

<div class="span8"></div>

回答by tymeJV

Since #saveis dynamically created, use the following handler:

由于#save是动态创建的,请使用以下处理程序:

$(document).on('click', '#save' ,function() {
    //do stuff
});

Updated fiddle: http://jsfiddle.net/tymeJV/YsnhT/3/

更新小提琴:http: //jsfiddle.net/tymeJV/YsnhT/3/

You should also make your "click" button handler like this, or else it will not fire on newly created #clickbuttons.

您还应该像这样制作“单击”按钮处理程序,否则它不会在新创建的#click按钮上触发。

回答by flavian

Simply delegate the event in dynamic format:

只需以动态格式委托事件:

$(document).on('click', '#save' ,function() {
    //do stuff
})

And perhaps do the same for:

也许对以下情况也做同样的事情:

$(document).on('click', '#click' ,function() {
    //do stuff
})

回答by PSR

save is creating dynamically here.So try to using on

保存在这里动态创建。所以尝试使用 on

$(document).on('click', '#save' ,function() {
});

回答by Maloric

Once you have appended the element you need to rebind the handlers to it or use jQuery's live() function, like so:

附加元素后,您需要将处理程序重新绑定到它或使用 jQuery 的 live() 函数,如下所示:

$('.span8 .btn').live('click', function() {
    var input = $("#textarea").val();
    alert(input);
});

回答by mathew

check this...

检查这个...

$('.btn').click(function() {

$('.btn').click(function() {

 var input = $("#textarea").val();
    alert(input);

});

});