我正在尝试使用addEventListener
click
两个按钮具有相同的class
,但它不起作用!
这是html:
<div class="share-block">
<a href="#" class="btn-rounded share-btn"><i class="fa fa-share-alt fa-2x"></i></a>
<div class="social-block">
<a href="http://facebook.com/share" class="btn-rounded btn-sm social-btn btn-fb"><i class="fa fa-facebook"></i></a>
<a href="http://twitter.com/share" class="btn-rounded btn-sm social-btn btn-tw"><i class="fa fa-twitter"></i></a>
</div>
</div>
这是javascript代码:
var socialBtns = document.getElementsByClassName('social-btn');
for (var i = 0; i < socialBtns.length; i++) {
socialBtns[i].addEventListener('click', function(event) {
window.open(socialBtns[i].href, "Share", "width=600,height=400");
event.preventDefault();
});
}
答案 0 :(得分:1)
在事件处理程序上使用this.href
,而不是在for循环中引用socialBtns
变量:
var socialBtns = document.getElementsByClassName('social-btn');
for (var i = 0; i < socialBtns.length; i++) {
socialBtns[i].addEventListener('click', function(event) {
window.open(this.href, "Share", "width=600,height=400");
event.preventDefault();
});
}
您还可以通过在for循环之外创建事件处理程序来改进现有代码:
var socialBtns = document.getElementsByClassName('social-btn');
for (var i = 0; i < socialBtns.length; i++) {
socialBtns[i].addEventListener('click', openSocialLink);
}
function openSocialLink(event) {
window.open(this.href, "Share", "width=600,height=400");
event.preventDefault();
}