将数组插入location.href

时间:2012-01-30 19:21:12

标签: javascript onclick location href setattribute

我有一个程序可以在表单上放置输入按钮。当用户单击该按钮时,onclick属性使用location.href将其定向到链接。

elementButton_1.setAttribute("onclick", "self.location.href='http://google.com'; return false");

我正在尝试将链接存储在数组中。 如何将数组插入位置调用?

示例:

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

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

2 个答案:

答案 0 :(得分: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];
    // ..
}

最好不要将可运行代码定义为字符串,以确保安全性和安全性。可维护性目的。

答案 1 :(得分:0)

我不完全确定我理解,但我认为你想要:

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