JavaScript 锚链接
我有一个 href/文本列表,我需要为其创建锚点,然后显示这些锚点。一切都很好,直到我真正点击任何一个锚点。他们每个人只打开最后一个 href 的选项卡。即,如果列表中最后一个元素的 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)
以前我尝试使用 .onClick
,但我一直遇到事件侦听器试图仅附加到 url 的问题。我非常愿意采用更干净的解决方案,尽管这涉及到比事件侦听器更简单的东西。
非常感谢。
I have a list of href / text that I need to make anchors for and then display those anchors. Everything is fine until I actually click any of the anchors. They each only open a tab for the last href. I.e. 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.
//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. I am very amenable to a cleaner solution though that involves something simpler than an eventlistener.
Thanks much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您大多只需要更改您的点击处理程序,以不使用不再有效的变量。以下是示例代码:
问题是事件侦听器函数中的任何变量在单击之前都不会被计算。因此,在这种情况下,您可以通过直接从单击的链接获取 url 来避免使用它们。
我希望您也意识到旧版本的 IE 不支持
addEventListener
。 此 Mozilla 页面向您展示了如何在 Internet Explorer 部分中处理该问题。You mostly just need to change your click handler to not use variables that are not still valid. Here's sample code:
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
. This mozilla page shows you how you can handle that in the Internet Explorer section.您需要创建一个闭包:
You need to create a closure: