简体   繁体   English

jQuery更改附加元素的父html

[英]jquery change parent html of appended element

Please help to adjust the code: 请帮助调整代码:

$('parent').click(function(){
    $(this).html('<button> child <button/>');

    $('button').click(function(){
        $(this).parent().html('some new html');
    });
});

I am trying to create the dynamic action conformation with jQuery. 我正在尝试使用jQuery创建动态动作构造。 For example user clicks DELETE (parent). 例如,用户单击DELETE(父级)。 DELETE then is changed to YES / NO (child button). 然后将DELETE更改为YES / NO(子按钮)。 User clicks NO and parent html is becoming DELETE again. 用户单击“否”,父html再次变为“删除”。

You can try delegated event handlers like 您可以尝试委托事件处理程序,例如

$(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')
})

Demo: Fiddle 演示: 小提琴

You could create a new jQuery element and then append this, you can then assign the click handler to only that element. 您可以创建一个新的jQuery元素,然后附加它,然后可以将click处理程序仅分配给该元素。

JSFiddle 的jsfiddle

$('#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!');
    });
});

Not the event.stopPropagation(); 不是event.stopPropagation(); in the child click handlers, this will stop the event bubbling up the DOM tree and re-executing the initial parent click. 在子点击处理程序中,这将停止事件在DOM树中冒泡并重新执行初始parent点击。

Why can't you use the JavaScript confirm popup box? 为什么不能使用JavaScript确认弹出框? That way you don't need to edit the DOM at all and lives are made easier :). 这样,您根本就不需要编辑DOM,生活变得更加轻松:)。

    $('parent').click(function(){
       var blnDelete = confirm("Do you want to delete?");
       if (blnDelete) {
         // Delete
       } else {
         // Don't Delete
       }
    });

http://www.w3schools.com/jsref/met_win_confirm.asp http://www.w3schools.com/jsref/met_win_confirm.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM