所以我有一个html文件,其中“添加”按钮创建标记为
的字段框<a id="document_create:nxl_item:nxw_referenceHeaderList:0:nxw...." class="button smallButton listWidgetActionAdd" onclick="return ... </a>
如果我一直点击“添加”按钮,则每次出现0时,ID名称都会不断变化。它可以是:
document_create:nxl_item:nxw_referenceHeaderList:0:nxw....
document_create:nxl_item:nxw_referenceHeaderList:1:nxw....
document_create:nxl_item:nxw_referenceHeaderList:2:nxw....
document_create:nxl_item:nxw_referenceHeaderList:2:nxw....
document_create:nxl_item:nxw_referenceHeaderList:3:nxw....
有没有办法可以提取ID名称而无需手动输入?就像一个循环或一个可以从类或东西中提取ID的函数?
任何帮助将不胜感激!谢谢!
答案 0 :(得分:0)
如果您展示了一些HTML上下文,那么帮助您会容易得多,但如果在之前的上下文之后添加新的上下文,您可以按类找到它们(假设它们的某些组合是唯一的)或基于它们在DOM结构中的位置,并使用最后一个:
var list = document.querySelectorAll("a.listWidgetActionAdd"),
last = list[list.length - 1];
if (last) {
// Use `last`, it's a reference to the element
// `last.id` is its `id` if you need it
}
直播示例:
var list = document.querySelectorAll("a.listWidgetActionAdd"),
last = list[list.length - 1];
if (last) {
// Use `last`, it's a reference to the element
// `last.id` is its `id` if you need it
document.body.innerHTML = "<code>last.id = " + last.id + "</code>";
}
<a id="document_create:nxl_item:nxw_referenceHeaderList:0:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="document_create:nxl_item:nxw_referenceHeaderList:1:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="document_create:nxl_item:nxw_referenceHeaderList:2:nxw...." class="button smallButton listWidgetActionAdd"></a>
重新评论:
我之前应该提到过,在字段中有另一个添加按钮,它正在被创建,具有类似的类。有什么方法可以区分它们吗?喜欢使用字符串RegExp?区别在于id名称不同......这有帮助吗?
如果它只是一个类似的类名,那么没有问题 - 只需使用其他类名。
如果它是相同的类名,那么是的,您可以使用id
来区分它们。例如,以上是使用attribute starts with选择器仅使用以a
开头的id
来查看document_create:nxl_item:nxw_referenceHeaderList
个元素:
var list = document.querySelectorAll("a[id^='document_create:nxl_item:nxw_referenceHeaderList']"),
last = list[list.length - 1];
if (last) {
// Use `last`, it's a reference to the element
// `last.id` is its `id` if you need it
document.body.innerHTML = "<code>last.id = " + last.id + "</code>";
}
var list = document.querySelectorAll("a[id^='document_create:nxl_item:nxw_referenceHeaderList']"),
last = list[list.length - 1];
if (last) {
// Use `last`, it's a reference to the element
// `last.id` is its `id` if you need it
document.body.innerHTML = "<code>last.id = " + last.id + "</code>";
}
<a id="document_create:nxl_item:nxw_referenceHeaderList:0:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="some-other-format:0:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="document_create:nxl_item:nxw_referenceHeaderList:1:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="some-other-format:1:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="document_create:nxl_item:nxw_referenceHeaderList:2:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="some-other-format:2:nxw...." class="button smallButton listWidgetActionAdd"></a>