将所有带有 id like 的元素放入数组中

Get all elements with id like into array

本文关键字:数组 元素 like id      更新时间:2023-09-26

我正在尝试返回一个包含所有元素的数组,其id以某个值开头,位于div内,并将其分配给变量,但我得到了Undefined is not a function例外。这是代码:

var stopPoints = $("#stop-point-content").querySelectorAll("[id^='stop-point-input-']");

HTML 元素在到达此代码行时确实存在(或至少一个)。

编辑:

在我的情况下,id就像stop-point-input-1stop-point-input-2等。这就是为什么我按id^='stop-point-input-'搜索 - 从任何值开始......请不要关注这里的css

jQuery包装的对象没有querySelectorAll,但find可以做到这一点:

var stopPoints = $("#stop-point-content").find("[id^='stop-point-input-']");

您也可以使用一个选择器完成相同的操作:

var stopPoints = $("#stop-point-content [id^='stop-point-input-']");

但这是一个好兆头,你应该改用一个类:

var stopPoints = $("#stop-point-content .stop-point-input");