简体   繁体   中英

insert array into location.href

I have a program that places input buttons on a form. When a user clicks on the button the onclick attribute uses location.href to direct it to a link.

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

I am trying to store the links in an array. How can i insert an array into the location call?

Example:

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

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

As long as elementButton_1 is defined, what you posted will work. However, a much better practice is:

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];
    // ..
}

It's better not to define runnable code as a string, for security & maintainability purposes.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM