简体   繁体   English

Javascript锚链接

[英]Javascript Anchor Link

I have a list of href / text that I need to make anchors for and then display those anchors. 我有一个href /文本列表,我需要制作锚点然后显示这些锚点。 Everything is fine until I actually click any of the anchors. 一切都很好,直到我实际点击任何锚点。 They each only open a tab for the last href. 它们每个只打开最后一个href的选项卡。 Ie if the href of the last element in the list is href_n, then every anchor links to href_n, even if the 'href' attribute is different. 即,如果列表中最后一个元素的href是href_n,则每个锚链接到href_n,即使'href'属性不同。

//Current basic setup:

loop through list:

anchor = doc.create('a')
divElem = doc.create('div')
anchor.setAttribute('class', 'foo')
anchor.setAttribute('href', 'bar')
anchor.innerHTML = 'mytext'
anchor.addEventListener('click', function() {chrome.tabs.create({url: 'myurl'})});
divElem.appendChild(anchor)
container.appendChild(anchor)

Previously I tried using .onClick , but I kept having a problem with the event listener trying to just attach to the url. 以前我尝试使用.onClick ,但我一直遇到问题,事件监听器试图只是附加到网址。 I am very amenable to a cleaner solution though that involves something simpler than an eventlistener. 虽然这涉及比eventlistener更简单的东西,但我非常适合更清洁的解决方案。

Thanks much. 非常感谢。

You mostly just need to change your click handler to not use variables that are not still valid. 您大多只需要更改单击处理程序以不使用仍然无效的变量。 Here's sample code: 这是示例代码:

var urlList = [
    "aaaa",
    "bbbb",
];

var textList = [
    "text1",
    "text2"
];

function createAnchors(urls, text, container) {
    for (var i = 0; i < urls.length; i++) {
        var a = document.createElement("a");
        var div = document.createElement("div");
        a.href = urls[i];
        a.innerHTML = text[i];
        a.className = "foo";
        a.addEventListener("click", function() {
            chrome.tabs.create({url: this.href}); 
            return(false);
        });
        div.appendChild(a);
        container.appendChild(div);
    }
}

The issue is that any variables in your event listener function are not evaluated until the click. 问题是,在单击之前,不会评估事件侦听器函数中的任何变量。 So, in this case, you can avoid using them by just getting the url directly from the clicked link. 因此,在这种情况下,您可以通过直接从点击的链接获取网址来避免使用它们。

I hope you also realize that older versions of IE don't support addEventListener . 我希望你也意识到旧版本的IE不支持addEventListener This mozilla page shows you how you can handle that in the Internet Explorer section. 这个mozilla页面向您展示了如何在Internet Explorer部分中处理它。

You need to create a closure: 你需要创建一个闭包:

var urls = [];
for(var i=0;i<urls.length;i++){
    anchor.addEventListener('click', 
        (function(url) {
            return function() {
                chrome.tabs.create({url: url})
            }
        })(urls[i])
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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