如何在javascript中打开mouseover事件的所有链接?

时间:2014-07-06 09:57:19

标签: javascript

我试过了:

for (i = 0; i < document.getElementsByTagName('a').length; i++) {

document.getElementsByTagName('a')[i].onmouseover= eval(function(){
window.open(document.getElementsByTagName('a')[i].href, "_blank");});
}

但是到达代码的这一部分时出了问题:&#34; window.open(document.getElementsByTagName(&#39; a&#39;)[i] .href&#34;

&#34;未捕获的TypeError:无法读取属性&#39; href&#39;未定义&#34;

编辑1:

我也试过这个:

var links = document.getElementsByTagName('a');

for (var i = 0; i < links.length; i++) {
    links[i].onmouseover = function(){window.open(links[i].href, "_blank")};
}

我得到了同样的错误:未捕获的TypeError:无法读取属性&#39; href&#39;未定义的

当我改变&#39; i&#39;到&#39; i-1&#39;对于window.open,每个链接都被页面上的最后一个链接替换,请参阅代码:

var links = document.getElementsByTagName('a');

for (var i = 0; i < links.length; i++) {
    links[i].onmouseover = function(){window.open(links[i-1].href, "_blank")};
}

2 个答案:

答案 0 :(得分:1)

这应该按预期工作:

var links = document.getElementsByTagName('a');

for (var i = 0; i < links.length; i++) {
    links[i].onmouseover = (
        function(h){
            return function(){ window.open(h, "_blank") }
        }
    )(links[i].href);
}

答案 1 :(得分:0)

为什么你得到Unable to get href of ......是因为元素可能是因为元素不是YET定义的。这意味着您应该将代码放在最后或将其添加到window.onload - 使用addEventListener代替onload

嗯,@ Arnauld的答案可能还不错,但我建议使用addEventListenerattachEvent,因为它可能会让您的编码更容易:)

var links = document.getElementsByTagName("a");

for (var i = 0; i < links.length; i++){
    if(links[i].addEventListener){ // Check if addEventListener is available
        links[i].addEventListener("mouseover", function(){
            window.open(links[i].href, "_blank");
        });
    }else{
        if(links[i].attachEvent){ // addEventListener not available; test attachEvent
            links[i].attachEvent("onmouseover", function(){
                window.open(links[i].href, "_blank");
            });
        }else{
            // Neither attachEvent nor addEventListener is available; Throw error (You can try to use links[i].onmouseover)
            throw new Error("!(addEventListener & attachEvent)");
        }
    }
}