javascript - 如何为单个元素添加 2 个 onclick 事件方法,该元素的类在 jquery 上的第一个单击事件方法上动态更改

标签 javascript jquery

在此单击事件中,它将单击的元素类从“fa-pencil-square-o”更改为“fa-floppy-o”。

$("i.fa.fa-pencil-square-o").click(function () {
    var parentid = $(this).parent().attr('id');
    var parent = $('tr#' + parentid);

    var rtn;
    var rtd;

    if (parent.find('td:nth-child(4)').text() == 'No') {

        rtn = parent.find('td:nth-child(2)').text();
        rtd = parent.find('td:nth-child(3)').text();

        parent.find('td:nth-child(2)').empty();
        parent.find('td:nth-child(3)').empty();

        //changes class here
        parent.find('td:nth-child(5)').empty();
        parent.find('td:nth-child(5)').append('<i class="fa fa-floppy-o" aria-hidden="true"></i>');


        parent.find('td:nth-child(2)').append('<input type="text" id="rtName" />');
        parent.find('td:nth-child(3)').append('<input type="text" id="rtDescription" />');

        $(parent).find('input#rtName').val(rtn);
        $(parent).find('input#rtDescription').val(rtd);
    }

});

当同一单击元素的类更改为“fa-floppy-o”时,我希望此单击事件生效,但它没有生效,并且仍然调用上面的第一个单击事件。

    $('.fa-floppy-o').click(function () {
    var parent = $(this).parent();
    var rtn = parent.find('input#rtName');
    var rtd = parent.find('input#rtDescription');

    $.ajax({
        url: '/editRoomType',
        async: false,
        type: 'POST',
        data: {
            roomTypeID: parent.attr('id'),
            roomTypeName: rtn.val(),
            roomTypeDescription: rtd.val()
        },
        dataType: 'json',
        success: function (data) {
            if (data.isSuccessful) {
                $('#msgdiv').css("display", "inline");
                $('#msg').empty();
                $('#msgdiv').removeClass('alert-danger');
                $('#msgdiv').addClass('alert-success');
                $.each(data.Message, function (key, value) {
                    $('#msg').append(value + '<br />')
                })
                $('.table-details tbody').empty();
                parent.find('td:nth-child(5)').empty();
                parent.find('td:nth-child(5)').append('<i class="fa fa-pencil-square-o" aria-hidden="true"></i>');
                getRoomType();

            } else {
                $('#msgdiv').css("display", "inline");
                $('#msg').empty();
                $('#msgdiv').removeClass('alert-success');
                $('#msgdiv').addClass('alert-danger');
                $.each(data.Message, function (key, value) {
                    $('#msg').append(value + '<br />')
                })
            }
        },
        error: function () {
            alert('error accounts')
        }
    });

});

我基本上想要完成的是当元素的类发生变化时,元素的单击事件函数也会发生变化。但如何呢?

最佳答案

您将监听器直接添加到具有提供的类的元素,而是使用 jQuery 的 on() 事件委托(delegate)将监听器添加到父元素,并提供单击的元素的类作为第二个参数。甚至 document 也能工作。

这是 jQuery on() 事件处理程序的定义:

.on( events [, selector ] [, data ], handler )

更改此行:

$("i.fa.fa-pencil-square-o").click(function () {

对此:

$(document).on("click", "i.fa.fa-pencil-square-o", function() {

这一行:

 $('.fa-floppy-o').click(function () {

对此:

$(document).on("click", ".fa-floppy-o", function() {

原因是:jQuery 在页面加载时添加这些监听器一次。因为它没有找到 .fa-floppy-o 类的任何内容,所以它不会添加监听器。重命名(重新分类)元素以及页面加载后由 jQuery/Javascript 动态生成的元素都是如此。

该事件将从该元素向上冒泡到父元素,并且该父元素将检查该元素是否具有第二个参数中提供的选择器。

有关事件冒泡的更多信息:

Direct and delegated events

The majority of browser events bubble, or propagate, from the deepest, innermost element (the event target) in the document where they occur all the way up to the body and the document element.

...

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

这里是 jQuery 中 on() 函数的文档:http://api.jquery.com/on/

关于javascript - 如何为单个元素添加 2 个 onclick 事件方法,该元素的类在 jquery 上的第一个单击事件方法上动态更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924468/

相关文章:

javascript - 如何使用Javascript访问不同域的数据

javascript - 如何重新打开语义 ui 模式?

Javascript setTimeout 失火

JQuery Datatable 将分页移至顶部

jQuery 日期选择器仅显示年月

javascript - 在 CoffeeScript 中定义 BootstrapValidator 回调

javascript - setTimeout 无法按 css 预期工作

javascript - Backbone 表格使用 Backbone 集合和选择编辑器的选项

javascript - 我可以更改参数还是操作是静态的/"locked down"吗?

javascript - `reduce/scan` 的累加器函数中的可观察类型是否匹配?