动态添加的jquery按钮不起作用

时间:2013-11-12 14:27:14

标签: jquery html dom button

我有两个jquery调用。第一个添加一个按钮到html,第二个添加按钮,如果单击添加按钮。问题是第二个根本不起作用。

html看起来像这样

<input type="button" id="add_button" value="Add the button">
<div id="results"></div>

脚本文件看起来像这样

$("#add_button").on('click', function () {
     $("#results").html('<input type="button" class="ok_button" value="OK">');
});
$(".ok_button").on('click', function () {
    alert('ok');
});

这里是fiddle

5 个答案:

答案 0 :(得分:2)

使用.on()

由于元素是动态添加的,因此无法将事件直接绑定到它们。因此,您必须使用Event Delegation

$('#results').on('click', '.ok_button', function() { ..code here.. }

语法

$( elements ).on( events, selector, data, handler );

Fiddle Demo

答案 1 :(得分:1)

由于动态添加ok_button,您需要使用event delegation注册事件处理程序,如: -

// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#results').on('click', '.ok_button', function() {
    alert('ok'); 
});

Fiddle Demo

答案 2 :(得分:1)

$("#add_button").click(function() {
    $newButton = $('<input type="button" class="ok_button" value="OK">');
    $newButton.click(function() {
        alert('ok');
    });
    $("#results").append($newButton);
});

工作示例:jsfiddle.net

答案 3 :(得分:1)

$(document).on('click', "#add_button", function (){
$("#results").append('<button type="button" class="ok_button">ok</button');

});
$(document).on('click', ".ok_button", function (){
alert("i know nothing");
});

答案 4 :(得分:1)

该代码段不起作用,因为在将元素添加到DOM之前事件已绑定到DOM。请尝试以下代码段:

$("#add_button").on('click', function () {
   $("#results").html('<input type="button" class="ok_button" value="OK">');
   $(".ok_button").off('click').on('click', function() {
       alert("ok");
   });
});