单击事件在 Class 更改后不起作用

Click Event Not Working After Class Change

我有以下脚本:

// dashboard maximize
$('#dashboard-actions .btn-maximize').click(function() {

    // max / restore buttons
    $(this).removeClass('btn-maximize').addClass('btn-restore');
    $(this).find('span').removeClass('icon-maximize').addClass('icon-restore');

    // swap tables
    $('#table-dashboard-actions-mini').hide();
    $('#table-dashboard-actions').show();

    // show form
    $('#form-dashboard-actions-btm').show();

    // restyle panel
    $(this).parents('.panel-dashboard').addClass('panel-dashboard-max');

    // animate panel
    $(this).parents('.panel-dashboard').animate({
            width: "100%",
        }, 250, function() {
        // Animation complete.
    });
    $(this).parents('.panel-primary').animate({
            height: "725px"
        }, 250, function() {
        // Animation complete.
    });

});

如您所见,脚本一度将单击按钮的 class 更改为 .btn-restore

但是这意味着我似乎无法将事件绑定到 .btn-restore

我原来有这个:

// dashboard restore
$('#dashboard-actions .btn-restore').click(function() {

    alert('asdf');
});

而且alert语句没有用,所以我改成这样:

$('#dashboard-actions .btn-restore').on('click', function() {

但还是没有喜悦。谁能看出我做错了什么?

试试这个:

$(document).on('click','#dashboard-actions .btn-restore', function() {

而不是:

$('#dashboard-actions .btn-restore').on('click', function() {

委托事件必须绑定到 dom 中存在的内容,第二部分将定义要触发点击的元素('#dashboard-actions .btn-restore')。

您需要使用 event delegation,因为 class 会动态变化。

$('#dashboard-actions').on('click','.btn-restore', function() {

最初绑定事件处理程序时,不存在具有 class btn-restore 的元素,因此 class 更改后的点击事件不会触发。

另外,我看到 btn-maximize 被改变了,这是后来的 added/toggled 我建议使用一个普通的 class 像 'btn-toggle' 然后 add/remove btn-maximize/btn-restore。这将阻止添加两个单独的事件处理程序。

勾选 Jquery Documentation

所以也许你需要放这样的东西。

使用#dashboard-actions 的子元素

$('#dashboard-actions .button').on('click', function() {})

并在函数内部使用 hasClass documentation

$(this).hasClass('className')

正如一些人提到的,事件委托是绑定到尚未匹配的选择器的关键。绑定到将始终存在的通用选择器 .button 然后在变量中保持状态(最大化或恢复)的替代建议也是有效的。

您的面板打开然后立即关闭的问题似乎是您立即在事件处理程序中添加了 .btn-restore class。它不应该发生,但似乎点击事件在新选择器上再次触发(可能与 click 事件的 mouseupmousedown 组件有关?)。我建议像这样将 addClass 调用包装在 setTimeout() 中,以确保 classes 被更改 任何事件触发后,本质上 "pushing"当前执行结束的变化:

var $btn = $(this);
setTimeout(function () {
    $btn.removeClass('btn-maximize').addClass('btn-restore');
    $btn.find('span').removeClass('icon-maximize').addClass('icon-restore');
});

您会注意到新变量 $btn。这是必需的,因为 setTimeout 函数中的 this 将不再引用单击的元素(如果需要,快速搜索 "javascript scope and this" 或类似内容将进一步解释这一点)。在任何情况下缓存 $(this) 结果也没有坏处。

希望对你有用 - 如果我能提供进一步的帮助,请告诉我。