使用javascript在链接内添加onclick事件

使用javascript在链接内添加onclick事件,javascript,Javascript,我需要在链接中添加onclickevent,这样链接看起来就像这样 <a href="/" onclick="parent.$.fn.colorbox.close();" target="_parent">mylink</a> 这是完整的代码 window.onload = function(){ var anchors = document.getElementsByTagName('a'); for (var i=0; i<anchors.length

我需要在链接中添加onclickevent,这样链接看起来就像这样

<a href="/" onclick="parent.$.fn.colorbox.close();" target="_parent">mylink</a>
这是完整的代码

window.onload = function(){
  var anchors = document.getElementsByTagName('a');
  for (var i=0; i<anchors.length; i++){
    anchors[i].setAttribute('target', '_blank');
    anchors[i].addEventListener('click', xxx, false); 
    }
}

谢谢。

由于这是一个锚定标记,您应该使用javascript附加事件,并使用preventDefault防止锚定标记的默认行为

例如:


元素定义在哪里?@NewToJS我添加了完整的代码。我试图更改页面锚[I]上的所有链接。添加了“单击”,xxx,false;将调用函数xxx,因此这应该可以工作。我很难理解你有什么问题。。。。您可以使用锚[i].setAttribute'onclick','parent.$.fn.colorbox.close';假设父项$.fn.colorbox.close;做了一些事情。@NewToJS嗨,setAttribute在链接中添加了onclick,但我想避免它,因为我读到并不是所有的浏览器都能正确处理它。嗨,在添加了您编写的内容之后,里面仍然没有onclick属性。target=\u blank的设置没有问题。如果使用javascript添加它,就不会有可以看到的onclick属性,但是,由于是通过编程方式添加的,所以单击它时,它将正常工作。请尝试打开chrome或firefox调试器,并在正在附加的onclick函数中设置断点。单击链接后,我收到错误Uncaught TypeError:无法读取控制台中此行未定义的属性“$”。e.target.parent。$.fn.colorbox.close;奇怪的是,如果我使用setAttribute添加onclick事件,一切都正常。
window.onload = function(){
  var anchors = document.getElementsByTagName('a');
  for (var i=0; i<anchors.length; i++){
    anchors[i].setAttribute('target', '_blank');
    anchors[i].addEventListener('click', xxx, false); 
    }
}
function yourFunction(e) {
   e.preventDefault(); // <---- this is important
   e.target.parent.$.fn.colorbox.close();
}
element.addEventListener('click', yourFunction, false);