0

我有两个 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');
});

这是小提琴

4

5 回答 5

2

使用.on()

由于元素是动态添加的,因此您不能将事件直接绑定到它们。因此您必须使用事件委托

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

句法

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

Fiddle Demo

于 2013-11-12T14:28:18.223 回答
1

该代码段不起作用,因为在将元素添加到它之前,该事件已绑定到 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");
   });
});
于 2013-11-12T16:45:34.917 回答
1

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

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

小提琴演示

于 2013-11-12T14:28:16.043 回答
1
$("#add_button").click(function() {
    $newButton = $('<input type="button" class="ok_button" value="OK">');
    $newButton.click(function() {
        alert('ok');
    });
    $("#results").append($newButton);
});

工作示例:jsfiddle.net

于 2013-11-12T14:54:04.390 回答
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");
});
于 2013-11-12T15:07:15.110 回答