gpt4 book ai didi

javascript - 为什么它只适用于第一个按钮?

转载 作者:行者123 更新时间:2023-11-30 11:50:54 25 4
gpt4 key购买 nike

我展示了这样一个项目列表:

enter image description here

为什么我的代码只适用于第一个按钮?当我点击另一个时,什么也没有发生。

$(document).ready(function() {
$("#js-toggle-attendance").click(function (e) {
var button = $(e.target);
$.post("/api/attendances", { gigId: button.attr("data-gig-id") }).done(function() {
button.removeClass("btn-default").addClass("btn-info").text("Ide");
}).fail(function() {
alert("Coś poszło nie tak :(");
});
});
});

最佳答案

我认为您在那个按钮中使用了相同的 id....那么您可以将其更改为类吗?

jQuery 中的 ID 选择器规则

Each id value must be used only once within a document. If more thanone element has been assigned the same ID, queries that use that IDwill only select the first matched element in the DOM. This behaviorshould not be relied on, however; a document with more than oneelement using the same ID is invalid.

查看DOC

jQuery ID 选择器中的 PATCH

使用属性选择器,您可以选择多个元素并在所有元素上绑定(bind)事件。在这里,我使用 [] 而不是 #id 传递了属性选择器。 这只是针对相同 id 的选择多个元素的补丁,根本不遵循此

 $("[id='js-toggle-attendance']").click(function (e) {
var button = $(this);
$.post("/api/attendances", { gigId: button.attr("data-gig-id") }).done(function() {
button.removeClass("btn-default").addClass("btn-info").text("Ide");
}).fail(function() {
alert("Coś poszło nie tak :(");
});
});

关于javascript - 为什么它只适用于第一个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39510049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com