gpt4 book ai didi

javascript - 通过名称或 ID 的一部分获取元素

转载 作者:行者123 更新时间:2023-12-02 23:53:15 24 4
gpt4 key购买 nike

这是我的表单示例(仅输入我想要的内容,但还有很多其他内容):

<form name="inputform" action="..." method="post">
<input type="hidden" name="id_qtedje_77" id="id_qtedje_77" value="0">
<input type="text" id="id_qte_77" name="prestation_detail_fields[77][qte_collecte]" value="0.00">
<input type="text" id="id_rec_77" name="prestation_detail_fields[77][reliquat_conforme]" value="0.00">
<input type="text" id="id_ren_77" name="prestation_detail_fields[77][reliquat_non_conforme]" value="0.00">
<input type="checkbox" name="prestation_detail_fields[77][dechet_non_present]" value="1">

<!-- another TR -->

<input type="hidden" name="id_qtedje_108" id="id_qtedje_108" value="0">
<input type="text" id="id_qte_108" name="prestation_detail_fields[108][qte_collecte]" value="0.00">
<input type="text" id="id_rec_108" name="prestation_detail_fields[108][reliquat_conforme]" value="0.00">
<input type="text" id="id_ren_108" name="prestation_detail_fields[108][reliquat_non_conforme]" value="0.00">
<input type="checkbox" name="prestation_detail_fields[108][dechet_non_present]" value="1">
</form>

我想要的是获取输入的值,但由于表单是用 PHP 构建的,我不知道行标识符 (77, 108)。

有没有办法做类似 getElementByName('id_qtedje_%') 的事情?

注意:我没有使用任何库,也不打算使用任何库。

最佳答案

你最好的选择可能是 document.querySelectorAll ,您可以使用任何 CSS 选择器,包括 "attribute starts with" selector就像input[id^="id_qtedje_"]。这是supported on all modern browsers, and also IE8 :

var elements = document.querySelectorAll('input[id^="id_qtedje_"]');

如果您只想要第一个匹配项(而不是列表),则可以使用 document.querySelector 代替。它返回对文档顺序中第一个匹配项的引用,如果没有匹配项,则返回 null。

或者,您可以为元素指定一个类名,然后使用 document.getElementsByClassName ,但请注意,虽然旧版本的 Chrome 和 Firefox 支持 getElementsByClassName,但 IE8 不支持它,所以它是 not as well-supported作为现代更有用的 querySelectorAll

var elements = document.getElementsByClassName("theClassName");

如果您使用任何库(jQuery、MooTools、Closure、Prototype 等),它们可能有一个功能,您可以使用它通过几乎任何 CSS 选择器查找元素,从而填补浏览器支持方面的空白他们自己的代码。例如,在 jQuery 中,它是 $ (jQuery) 函数;在 MooTools 和 Prototype 中,它是 $$

关于javascript - 通过名称或 ID 的一部分获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15874630/

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