使用 jQuery 使用 id 数组选择元素

Selecting elements in using jQuery using an array of id's

本文关键字:使用 元素 选择 id jQuery 数组      更新时间:2023-09-26

我有一个像这样的id数组:

answerIds = ['0', '5', '20']

我希望创建一个如下所示的jquery选择器:

$('.answer-reason[data-choice-id="' + answerId + '"]');

其中answerIdanswerIds 中的值。

换句话说,我希望它返回元素:

.answer-reason[data-choice-id="0"]
.answer-reason[data-choice-id="5"]
.answer-reason[data-choice-id="20"]

我该怎么做?

注意 我希望我的最终结果是一个jQuery对象。

换句话说,我应该能够做到这一点:

$output.on('click', function() { ... })`

例如

var el = [];
$.each(answerIds, function(index, element){ 
  el.push($('.answer-reason[data-choice-id="' + element + '"]'));
});

这应该可以。根据您的示例,变量 el 将具有所有三个元素。