Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

javascript - OnClick without jQuery

How to make onclick without jQuery, with no extra code in HTML, such as:

<a href="#" onclick="tramtramtram">

Just using an external js file?

<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;
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When this anchor will contain only one function to handle on click, than you can just write

document.getElementById('anchorID').onclick=function(){/* some code */}

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

also remember to call the above code when all elements are loaded (eg. on window.onload)

-- edit

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;});

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});
      }
   }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...