简体   繁体   中英

How do I bind a click to an anchor without a framework (javascript)

I know this is easily done in jQuery or any other framework, but that's not really the point. How do I go about 'properly' binding a click event in pure javascript? I know how to do it inline (I know this is terrible)

<a href="doc.html" onclick="myFunc(); return false">click here</a>

and this causes my javascript to execute for a JS enabled browser, and the link to behave normally for those without javascript?

Now, how do I do the same thing in a non-inline manner?

If you need to assign only one click event, you can assign onclick :

If you have an ID:

myAnchor = document.getElementById("Anchor");
myAnchor.onclick = function() { myFunc(); return false; }

you can also walk through all anchors:

anchors = document.getElementsByTagName("a");

for (var i = 0; i < anchors.length; i++) {   

 anchors[i].onclick = .....

}

There's also a document.getElementsByClassName to simulate jQuery's class selector but it is not supported by all browsers.

If it could be that you need to assign multiple events on one element, go with addEventListener shown by @Jordan and @David Dorward.

The basic way is to use document.getElementById() to find the element and then use addEventListener to listen for the event.

In your HTML:

<a href="doc.html" id="some-id">click here</a>

In your JavaScript:

function myFunc(eventObj) {
  // ...
}

var myElement = document.getElementById('some-id');
myElement.addEventListener('click', myFunc);

Or you can use an anonymous function:

document.getElementById('some-id').addEventListener('click', function(eventObj) {
  // ...
});

This is a nice cross-browser method

var on = (function(){
    if ("addEventListener" in window) {
        return function(target, type, listener){
            target.addEventListener(type, listener, false);
        };
    }
    else {
        return function(object, sEvent, fpNotify){
            object.attachEvent("on" + sEvent, function(){
                fpNotify(window.event);
            });
        };
    }
}());


on(document.getElementById("myAnchor"), "click", function(){
    alert(this.href);
});

这个问题的标准是关于怪癖模式: http ://www.quirksmode.org/js/events_advanced.html

给它一个 ID,你应该能够做到:

document.getElementById("the id").onclick = function{ ... }

Thanks to Pekka, remember binding listeners to entire array of elements with a certain class, rapidly increases the number of events bound to elements.

use the for loop in a faster way:

for (var i = Things.length - 1; i >= 0; i--) {
    Things[i]
};

the first expression of for loop will calculate only one time, so in this way, it won't through the DOM and calculate the length of array, besides, because of stack structure stepping on Arrays in reverse is faster then stepping forward.

You don't have to use jQuery, but you could try John Resig's popular addEvent funciton.

addevent(elem, "click",clickevent);  

function addEvent ( obj, type, fn ) {
      if ( obj.attachEvent ) {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
        obj.attachEvent( "on"+type, obj[type+fn] );
      } else
        obj.addEventListener( type, fn, false );
    }

There are more to be considered to'properly' bind an event on HTML tags in pure javascript.

http://www.pagecolumn.com/javascript/bind_event_in_js_object.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM