当元素上有多个类时触发按钮单击事件

Fire button click event when there are multiple classes on an element

本文关键字:按钮 单击 事件 元素      更新时间:2023-09-26

当按下特定按钮(在本例中为接受按钮)时,我将如何触发按钮单击事件。

我尝试了以下方法,但收效甚微:

爪哇语

$('.notification-expand .Request .active-item > .accept-button').click(function () {
    alert("hello");
});

.HTML

<div class="notification-expand Request active-item" style="display: block;">
    <div class="notification-body"></div>
    <br>
    <p>
        <button type="button" class="btn btn-success accept-button btn-sm">Accept</button>
    </p>
    <div class="row">
        <div class="col-xs-6 expand-col">
            <button type="button" class="btn btn-warning barter-button btn-sm">Barter</button>
        </div>
        <div class="col-xs-6 expand-col">
            <button type="button" class="btn btn-danger reject-button btn-sm">Reject</button>
        </div>
    </div>
</div>

在这里摆弄

你的选择器有错误,它应该看起来像这样:

$('.notification-expand.Request.active-item .accept-button').click(function () {
    alert("hello");
});

您需要连接所有没有空格的类来捕获目标按钮

$('button.accept-button', '.notification-expand.Request.active-item').click(function () {
    alert("hello");
});

查看更新的代码段

请注意".className1.className2"

而不是".className1 .className2"的语法

应该是这样的:

$('button.accept-button').click(function(){ ... });

如果这是整个代码,则真的没有必要进入整个列表

----编辑----

因此,当有更多项目但只有 1 个活动(我猜)时,只需针对活动项目类:

$('div.active-item button.accept-button').click(function(){ ... });

尝试

$('.accept-button', $('.notification-expand.active-item')).click(function () {
    alert("hello");
});

$('.notification-expand.active-item')).find('.accept-button').click(function () {
    alert("hello");
});

只需给按钮一个 id 并引用它即可。

.HTML

<button id="btnSubmitData"> Ok Button </button>

JQuery Code

$('#btnSubmitData').click(function(){ ... });

还可以将多个按钮 ID 绑定到同一事件:

$('#btnAccept, #btnReject, #btnWarning').click(function () {
        alert("hello");
    });

看看更新的工作小提琴。