0
我已經編寫了一個函數,可以在輸入元素中自動插入一個屬性(即每種情況適配onclick函數)。它也有一些例外。看起來像這樣,出於清晰的原因有點簡化:如何在我的setAttribute函數中內建數組子函數?
function insertAttribute() {
var allInputs = document.getElementsByTagName('input');
var allInputsCount = allInputs.length;
var thatInput = null;
for (i = 0; i < allInputsCount; i++) {
thatInput = allInputs[i];
var highlightFunction = "highlightItem('"+thatInput.name+"-row','"+thatInput.name+"-button')";
if ((thatInput.name != "A") && (thatInput.name != "B") && (thatInput.name != "C"))
thatInput.setAttribute("onclick",highlightFunction);
}
}
問題是,有大約20個例外。我可以擴大if
這一行,但我寧願用數組來做。但我該怎麼做?我一派how to use array in javascript function
,和(二頂部)的研究結果表明我應該做這樣的:
function insertAttribute() {
var allInputs = document.getElementsByTagName('input');
var allInputsCount = allInputs.length;
var thatInput = null;
for (i = 0; i < allInputsCount; i++) {
thatInput = allInputs[i];
var highlightFunction = "highlightItem('"+thatInput.name+"-row','"+thatInput.name+"-button')";
var exceptedArray = ["A","B","C"];
if (thatInput.name != exceptedArray)
thatInput.setAttribute("onclick",highlightFunction);
}
}
但是,這並不工作 - 屬性仍插在例外。應該怎麼做?我需要一個vanilla腳本解決方案。我也會很高興有一個很好的教程。正如你可能猜到的,這是我第一次使用這樣的數組子功能。
你可以試試'exceptedArray.indexOf(thatInput.name)== - 1',請參見[MDN陣列(https://developer.mozilla.org/更多功能en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) – Grundy
這似乎工作正常!謝謝,格蘭迪! –
您的解決方案目前工作良好,對此我仍然很感激,但是當我在IE8中進行測試時並不感謝。有關詳細信息,請參閱下面的帖子。 –