[英]Get element by part of Name or ID
這是我的表單示例(只有我想要的輸入,但還有很多其他輸入):
<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 選擇器,包括“屬性開頭為”選擇器,如input[id^="id_qtedje_"]
。 所有現代瀏覽器以及 IE8 都支持它:
var elements = document.querySelectorAll('input[id^="id_qtedje_"]');
如果您只想要第一個匹配項(而不是列表),則可以改用document.querySelector
。 它返回對文檔順序中第一個匹配項的引用,如果沒有匹配項,則返回null
。
或者,您可以為元素指定一個類名,然后使用document.getElementsByClassName
,但請注意,雖然舊版本的 Chrome 和 Firefox 支持getElementsByClassName
,但 IE8 沒有它,因此它的支持不如更多-現代有用的querySelectorAll
。
var elements = document.getElementsByClassName("theClassName");
如果您使用任何庫(jQuery、MooTools、Closure、Prototype 等),它們很可能有一個函數,您可以使用它來通過幾乎任何 CSS 選擇器查找元素,用它們自己的代碼填補瀏覽器支持方面的空白. 例如,在 jQuery 中,它是$
( jQuery
) 函數; 在 MooTools 和 Prototype 中,它是$$
。
var listOfElements = $('[name^="id_qtedje_"]')
使用querySelectorAll
,你可以做
document.querySelectorAll('[name^="id_qtedje_"]')
或者:
假設所有元素都是input
s,你可以使用這個:
function getElementByNameStart(str) {
var x=document.getElementsByTagName('input')
for(var i=0;i<x.length;i++) {
if(x[i].indexOf(str)==0) {
return x[i];
}
}
}
可以稱為 getElementByNameStart("id_qtedje_")
請注意,這僅返回此類型的第一個元素。 全部返回:
function getElementByNameStart(str) {
var x=document.getElementsByTagName('input')
var a=[];
for(var i=0;i<x.length;i++) {
if(x[i].indexOf(str)==0) {
a.push(x[i])
}
}
return a;
}
如果元素是任何類型,請將“輸入”替換為“*”(請注意,這可能會使您的代碼變慢)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.