我有一个奇怪的困境,我无法将 onclick
添加到 anchor 标记。我必须添加事件监听器/附加事件。我希望能够将一个类添加到 anchor ,并在文档准备好后创建一个事件监听器并使其打开链接 URL 的弹出窗口。所以我需要收集 anchor ,收集 URL,并使其在新窗口中打开。
我尝试使用 jQuery/JavaScript 组合创建它:
自定义脚本 jQuery/JS
$(document).ready(function() {
$numClass = document.getElementsByClassName('popUp');
$className = 'popUp';
$left = (screen.width/2)-(650/2);
$top = (screen.height/2)-(400/2);
alert($className[1]);
for(i = 0; i < $numClass; i++)
{
if($className[i].addEventListener)
{
$className[i].addEventListener('click', function(e){
getHref();
},true);
}
else{
$className[i].attachEvent('click', getHref);
}
}
function openWindow($url){
window.open(url, "location=1,status=1,scrollbars=1,width=650,height=400,left="+left+",top="+top);
}
function getHref(){
$href = className.getAttribute('href');
openWindow($href);
}
});
但事实证明长度只是调出字符。然后我在网上找到了这个脚本:
在线脚本
$(document).ready(function() {
var elArray = document.getElementsByTagName('a');
for(var i=0; i<elArray.length; i++){
if(elArray[i].className == 'popUp') continue;
for(var j=0; j<elArray.length; j++){
elArray[j].onclick = function(){
alert(this.innerHTML + ' : ' + this.href);
};
}
}
});
这要短得多,但它就是行不通,没有错误就是行不通。有人对此有任何修复吗?
我的整个 HTML 文档
<html>
<head>
<script type="text/javascript" src="jquery1.6.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var elArray = document.getElementsByTagName('a');
for(var i=0; i<elArray.length; i++){
if(elArray[i].className == 'popUp') continue;
for(var j=0; j<elArray.length; j++){
elArray[j].onclick = function(){
alert(this.innerHTML + ' : ' + this.href);
};
}
}
});
</script>
</head>
<body>
<a href="http://www.yahoo.com" class="popUp">test1</a>
<a href="http://www.google.com" class="popUp">test2</a>
<a href="http://www.msn.com" class="popUp">test3</a>
</body>
</html>
最佳答案
这应该可以解决问题:
$(document).ready(function() {
$('.popUp').on('click', function() {
openWindow(this.href);
return false;
});
});
function openWindow(url){
var left = (screen.width/2)-(650/2);
var top = (screen.height/2)-(400/2);
window.open(url, '_blank', "location=1,status=1,scrollbars=1,width=650,height=400,left="+left+",top="+top);
}
关于javascript - 将事件监听器添加到带有类 + 弹出 URL 的 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9728540/