![](/img/trans.png)
[英]How to use JavaScript's setattribute to affect multiple elements?
[英]how to setAttribute(s) for multiple tags at once
我將如何設置3個單獨的輸入標記以立即禁用? 用戶輸入時間后,我想禁用輸入字段,然后在時間用完時啟用它們。 我知道如何添加邏輯,但我很難一次將“禁用”添加到所有邏輯。
<div id="inputFields">
<h3>Enter Time</h3>
<input id="hours" type="text" value="" name="hours" placeholder="Hours" maxlength="2"> <span>:</span>
<input id="minutes" type="text" value="" name="min" placeholder="Minutes" maxlength="2"> <span>:</span>
<input id="seconds" type="text" value="" name="seconds" placeholder="Seconds" maxlength="2">
</div>
我需要遍歷它們嗎? 還是可以將它們作為#inputFields的子級來訪問? 還是沒有? 任何建議將不勝感激...謝謝。
如果您使用的是jQuery:
$('#inputFields > input').prop('disabled', true);
它將為#inputFields
的直接后代的每個input
設置屬性。
另外一個選項:
$('#hours,#minutes,#seconds').prop('disabled', true);
或者,如果使用純Javascript:
['hours', 'minutes', 'seconds'].forEach(function (elemId) {
document.getElementById(elemId).setAttribute('disabled', true);
});
應該也不錯。 這與您可以立即獲得的“所有這些”非常接近。
這是一種遍歷它們的方法,您可以對它們執行任何操作。
$('#inputFields').children('input').each(function () {
alert(this.value);
});
例如
$(this).prop('disabled', true);
不必將input
元素打包到div
,您可以適當地使它們成為form
元素的子元素。
這樣做的好處是,HTML中已經有一個form
元素集合,您可以使用document.forms[ ]
或僅使用forms[ ]
輕松地在JavaScript中進行訪問,並使用forms[ ].elements[ ]
輕松訪問其子級。
表單及其兒童可以通過其索引或name
屬性來調用,例如
var firstInput = forms['myInputForm'].elements[0];
例如,這樣您就可以遍歷此選擇並執行所需的任何更改。
編輯
鑒於事實,無論如何,您的input
元素確實具有name
屬性,您可以這樣寫
['hours', 'min', 'seconds'].forEach(function (name) {
document.forms['inputFields'].elements[name].setAttribute('disabled', true);
});
在您的腳本和<form name="inputFields">
而不是HTML中的div
中。
對於包含input
元素, form
元素比div
元素更適合,並且如前所述,您不必在整個DOM中搜索input
元素,因為已經有了HTML集合,可以使用JavaScript來訪問它。如上所述的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.