请帮助调整代码:
$('parent').click(function(){
$(this).html('<button> child <button/>');
$('button').click(function(){
$(this).parent().html('some new html');
});
});
我正在尝试使用jQuery创建动态操作构造。例如,用户单击DELETE(父级)。 DELETE然后更改为YES / NO(子按钮)。用户单击否,父html再次变为DELETE。
答案 0 :(得分:1)
您可以尝试委派的事件处理程序,例如
$(document).on('click', '.delete', function () {
$(this).replaceWith($('<span />', {
html: '<button class="yes">Yes</button><button class="no">No</button>'
}))
})
$(document).on('click', '.no', function () {
$(this).parent().replaceWith($('<button />', {
text: 'Delete',
'class': 'delete'
}))
})
$(document).on('click', '.yes', function () {
console.log('delete')
})
演示:Fiddle
答案 1 :(得分:0)
您可以创建一个新的jQuery元素然后追加它,然后您可以将click处理程序分配给该元素。
$('#parent').click(function(){
var yesBtn = $('<button type="button">Yes</button>');
var noBtn = $('<button type="button">No</button>');
$(this).html('');
$(this).append(yesBtn);
$(this).append(noBtn);
$(yesBtn).click(function(){
event.stopPropagation();
// On yes event handler
$(this).parent().html('You clicked Yes!');
});
$(noBtn).click(function(){
event.stopPropagation();
// On no event handler
$(this).parent().html('You clicked No!');
});
});
不是子点击处理程序中的event.stopPropagation();
,这将阻止事件冒泡DOM树并重新执行初始parent
点击。
答案 2 :(得分:0)
为什么不能使用JavaScript确认弹出框?这样你根本不需要编辑DOM,生活变得更容易:)。
$('parent').click(function(){
var blnDelete = confirm("Do you want to delete?");
if (blnDelete) {
// Delete
} else {
// Don't Delete
}
});