没有 jQuery 的 OnClick [英] OnClick without jQuery
本文介绍了没有 jQuery 的 OnClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何制作onclick
无 jQuery,在HTML中没有额外的代码,如:
How to make onclick
without jQuery, with no extra code in HTML, such as:
<a href="#" onclick="tramtramtram">
只使用外部js文件?
<script type="text/javascript" src="functions.js"></script>
<小时>
我需要替换这段代码:
I need to replace this code:
$("a.scroll-up, a.scroll-down").click(function(){
SNavigate($(this).attr("href").substr(7));return false;
});
推荐答案
当这个锚点只包含一个处理点击的函数时,你可以写
When this anchor will contain only one function to handle on click, than you can just write
document.getElementById('anchorID').onclick=function(){/* some code */}
否则,你必须使用 DOM 方法 addEventListener
otherwise, you have to use DOM method addEventListener
function clickHandler(){ /* some code */ }
var anchor = document.getElementById('anchorID');
if(anchor.addEventListener) // DOM method
anchor.addEventListener('click', clickHandler, false);
else if(anchor.attachEvent) // this is for IE, because it doesn't support addEventListener
anchor.attachEvent('onclick', function(){ return clickHandler.apply(anchor, [window.event]}); // this strange part for making the keyword 'this' indicate the clicked anchor
还记得在加载所有元素时调用上述代码(例如在 window.onload 上)
also remember to call the above code when all elements are loaded (eg. on window.onload)
--编辑
我看到你添加了一些细节.如果你想替换下面的代码
I see you added some details. If you want to replace the code below
$("a.scroll-up, a.scroll-down").click(function(){SNavigate($(this).attr("href").substr(7));return false;});
对于不使用 jQuery 的东西,这应该可以完成工作
with sth that doesn't use jQuery, this should do the job
function addEvent(obj, type, fn) {
if (obj.addEventListener)
obj.addEventListener(type, fn, false);
else if (obj.attachEvent)
obj.attachEvent('on' + type, function() { return fn.apply(obj, [window.event]);});
}
addEvent(window, 'load', function(){
for(var i=0, a=document.anchors, l=a.length; i<l;++i){
if(a[i].className == 'scroll-up' || a[i].className == 'scroll-down'){
addEvent(a[i], 'click', function(e){ SNavigate(this.href.substr(7)); e.returnValue=false; if(e.preventDefault)e.preventDefault();return false});
}
}
});
这篇关于没有 jQuery 的 OnClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文