将数组插入location.href

insert array into location.href

本文关键字:href location 插入 数组      更新时间:2023-09-26

我有一个程序,可以在表单上放置输入按钮。当用户单击按钮时,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");

只要定义了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];
    // ..
}

为了安全起见,最好不要将可运行代码定义为字符串;可维护性目的。

  • 引用元素.onclick()MDN

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

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