所以我有一个奇怪的问题,我无法添加onclick到锚标签。我必须添加事件监听器/附加事件。我希望能够在锚中添加一个类,并在文档准备好之后 - 创建一个事件监听器并使其打开一个链接URL的弹出窗口。所以我需要收集锚点,收集URL,并在新窗口中打开它。
我尝试使用jquery / javascript mix创建它:
$(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>
<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>
答案 0 :(得分:3)
这应该可以解决问题:
$(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);
}
答案 1 :(得分:1)
这应该有效:
$(document).ready(function() {
$('a.popup').click(function(event) {
event.preventDefault();
openWindow($(this).attr('href');
});
});
答案 2 :(得分:1)
$(document).ready(function() {
$('.popUp').click(openWindow)
});
function openWindow(){
var left = (screen.width/2)-(650/2);
var top = (screen.height/2)-(400/2);
window.open(this.href, "location=1,status=1,scrollbars=1,width=650,height=400,left="+left+",top="+top);
return false;
}