2012-01-30 43 views
0

我有一個將輸入按鈕放置在窗體上的程序。當用戶點擊按鈕時,onclick屬性使用location.href將其引導至鏈接。我想將鏈接存儲在數組中。 如何將數組插入位置調用?將數組插入到位置.href

例子:

locationArray = new Array(); 
locationArray[0] = "http://google.com"; 

elementButton_1.setAttribute("onclick", "self.location.href=locationArray[0]; return false"); 
+0

例如,您的作品,因爲要的setAttribute第二個參數會JS代碼進行評估.. – paislee 2012-01-30 19:40:39

回答

0

我不能完全肯定我理解,但我想你想:

elementButton_1.setAttribute("onclick", "self.location.href='" + locationArray[0] +"'; return false"); 
+0

那正是我一直在尋找THX – alphadev 2012-01-30 19:37:17

+1

最初的例子工程,以及這個建議。 – paislee 2012-01-30 19:51:40

+0

我甚至沒有考慮過!非常真實。我不知道如何給自己的回覆添加註釋,但通常情況下,您不應該使用構造函數窗體,而是使用數組文本來實例化您的數組。 http://answers.oreilly.com/topic/2151-when-to-use-the-array-literal-notation-in-javascript/ – 2012-01-30 19:55:27

1

只要elementButton_1定義,你貼什麼工作。然而,一個更好的做法是:

locationArray = new Array(); 
locationArray[0] = "http://google.com"; 

var elementButton_1 = document.getElementById('mybutton'); 

// define a click handler for the button 
elementButton_1.onclick = function() { 
    self.location.href = locationArray[0]; 
    // .. 
} 

這是最好不要來定義可運行代碼的字符串,安全&可維護性的目的。