简体   繁体   中英

Open multiple links on a webpage using javascript

I have a webpage which has multiple links. What I want to do is I want to open all the links in different windows using javascript. As of now, my code looks like below. All the links have common calss "myClass" and different "id".

$( document ).ready(function() {

var elements = document.getElementsByClassName("myClass");

for (var i = 0; i < elements.length; i++) {

    alert(elements[i].getAttribute("id"));

    $(elements[i].getAttribute("id")).onclick();
}})

What am I doing wrong? Could anyone help me on this. Any help would be much appreciated.

Instead of taking the id and trying invoke onclick() event manually, you can retrieve the href attribute and pass it to the window.open method.

for (var i = 0; i < elements.length; i++) {

    var url = elements[i].getAttribute("href");

    window.open(url);
}})

Read more about window.open here. https://developer.mozilla.org/en-US/docs/Web/API/Window.open

However, this might not be well accepted by the browsers, I suspect that they will prevent opening that many windows via javascripts. (Blocking Popups).

It looks like you are using jQuery, so a simple solution would be

$(".myClass").each(function() {
    window.open(this.href); 
});

Otherwise a pure JavaScript approach would be

var elements = document.getElementsByClassName("myClass");
for (var i=0; i<elements.length; i++) {
    window.open(elements[i].getAttribute("href"));
}

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