2013-11-22 31 views
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腳本解決方案。我也會很高興有一個很好的教程。正如你可能猜到的,這是我第一次使用這樣的數組子功能。

+0

你可以試試'exceptedArray.indexOf(thatInput.name)== - 1',請參見[MDN陣列(https://developer.mozilla.org/更多功能en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) – Grundy

+0

這似乎工作正常!謝謝,格蘭迪! –

+0

您的解決方案目前工作良好,對此我仍然很感激,但是當我在IE8中進行測試時並不感謝。有關詳細信息,請參閱下面的帖子。 –

回答

0

評論中提供的解決方案exceptedArray.indexOf(thatInput.name)==-1適用於大多數瀏覽器,但不適用於IE8。它的腳本調試器說它不支持indexOf。它在其他情況下,但顯然不在這種情況下。

與此同時,我學會了如何使腳本循環通過一個數組我自己。而這部作品在所有的瀏覽器:

var allInputs = document.getElementsByTagName('input'); 
var allInputsCount = allInputs.length; 
var thatInput = null; 
for (var i=0; i<allInputsCount; i++) { 
    thatInput = allInputs[i]; 
    var highlightFunction = "highlightItem('"+thatInput.name+"-row','"+thatInput.name+"-button')"; 
    var exceptedNamesArray = ["A","B","C","A4dTInput","A4eTInput"]; 
    var excNamesArrayCount = exceptedNamesArray.length; 
    var excName = null; 
    for (var j=0; j<excNamesArrayCount; j++) { 
     excName = exceptedNamesArray[j]; 
     if (thatInput.name != excName) 
     thatInput.setAttribute("onclick",highlightFunction); 
    } 
} 
相關問題