gpt4 book ai didi

javascript - 如何使用 HTML 属性填充 javascript 数组?

转载 作者:行者123 更新时间:2023-12-01 08:32:22 27 4
gpt4 key购买 nike

我的表行中有带有属性“结果 ID”的复选框。如何使用表行内“result-id”复选框中存储的值填充 JavaScript 数组。

我已经弄清楚如何访问 jquery 中的数据,现在我只想将该数据存储在数组中。

它看起来有点像这样:

   <td>
<input result-id="@item.Id" type="checkbox" />
</td>

这是我现在的jquery,它只添加一项(最后单击的复选框ID)

        $(tableBody).find('tr').each(function () {
if ($(this).find('input:checkbox').prop("checked") == true) {
resultList.fill(parseInt($(this).find('input:checkbox').attr('result-id')));
}
});

最佳答案

您想要:

  • 过滤掉未选中的复选框(:not(:checked).filter,...)
  • 在结果上使用 map 来获取包含 result-id 值的 jQuery 集(通过返回 this.getAttribute("result-id")$(this).attr("result-id"))
  • 使用 get 来获取实际的数组

例如:

var array = $(tableBody).find("tr input:checkbox:not(:checked)")
.map(function() {
return this.getAttribute("result-id");
})
.get();

它使用 jQuery 特定的 :checked 伪类来仅查看选中的复选框,并直接使用 DOM 来获取属性值。

您也可以在不使用 jQuery 特定选择器的情况下完成此操作:

var array = $(tableBody).find("tr input[type=checkbox")
.filter(function() { return this.checked; })
.map(function() {
return this.getAttribute("result-id");
})
.get();

或者根本不使用 jQuery(这里我假设 tableBody 是一个 DOM 元素,而不是 jQuery 集,并且是一个现代浏览器):

const array = Array.from(tableBody.querySelectorAll("tr input[type=checkbox"))
.filter(({checked}) => checked)
.map(cb => cb.getAttribute("result-id"));

关于javascript - 如何使用 HTML 属性填充 javascript 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60058318/

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