为多个id创建onclick事件



我写了一个js函数:

$(document).on('click', '#id1', function () {
$.ajax({
type: "POST",
url: "/url",
data: { uInput: 'id1' },
success: function (response) {
some code....
},
error: function (error) {
console.log(error);
}
});
});

问题是,因为我有更多的可点击对象与各种id,我想创建一个单一的脚本/函数,将接受onclick事件从不仅#id1,但也#id2, #id3等…

我试着遵循这里的建议:https://stackoverflow.com/a/18508894/11271927这里https://stackoverflow.com/a/18508907/11271927但是每当我编辑代码以适应我的代码结构时,它就不起作用了。

var options = {
id1: 'id1',
id2: 'id2',
id3: 'id3',
id4: 'id4'
};
$('.options').click(function () {
$.ajax({
type: "POST",
url: "/url",
data: options[this.id],
success: function (response) {
some code....
},
error: function (error) {
console.log(error);
}
});
});

基本上,这段代码在点击时没有做任何事情。

如果你知道我有什么遗漏或做错了,请帮助。

如果您想让一个函数对多个元素(例如按类)具有单击侦听器,您可以这样尝试:

<button class="button" id="id1">A</button>
<button class="button" id="id2">B</button>
<button class="button" id="id3">C</button>
<script>
$(document).on('click', '.button', function () {
$.ajax({
type: "POST",
url: "/url",
data: {
uInput: this.getAttribute('id'),
},
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
});
</script>

您可以在文档上设置单个click事件侦听器,并在其函数中使用条件来将相同的语句块应用于任何元素组。

例如,您可以筛选id以字符串"id"开头的目标。像这样(core js):

document.addEventListener('click', event => {
if (event.target.id.indexOf('id') == 0) {
// commands to apply to those elements;
} // end if #id* click;
// any number of other groups or individual elements can be added, each with a conditional to filter the required ones.
}); // end event listener

如果需要更具体的内容,可以细化条件,例如(在文档事件侦听器函数中):

const id=event.target.id;
if (id == "id1" || id == "id3" || id == "somethingElse") {
// relevant statements;
};

我通常默认使用文档事件侦听器,没有额外的计算成本,而且我发现单个事件侦听器更容易维护。