在jquery1.71中,不推荐使用.live().尽管如此,它仍然有效
var toggleBtn = document.createElement('input');
toggleBtn.id = 'toggleBtn';
toggleBtn.type = 'button';
toggleBtn.value = 'Close';
box.appendChild(toggleBtn);
$('#toggleBtn').live('click', function() {
alert("hihi");
});
Run Code Online (Sandbox Code Playgroud)
我尝试了推荐的.on().奇怪的是,这失败了
var toggleBtn = document.createElement('input');
toggleBtn.id = 'toggleBtn';
toggleBtn.type = 'button';
toggleBtn.value = 'Close';
box.appendChild(toggleBtn);
$('#toggleBtn').on('click', function() {
alert("hihi");
});
Run Code Online (Sandbox Code Playgroud)
请务必完整阅读文档.为了.on()像.live()(或.delegate())那样工作,第二个参数必须是委托给的选择器.
$(document).on('click', '#toggleBtn', function () {});
Run Code Online (Sandbox Code Playgroud)
当然,您可以使用更具体的选择器.