문제

when i use the .preventDefault on a link it still goes to the link - also is this even doable with JS or is it a jquery only method?

var avoidlink = getElementsByTagName("a");

avoidlink.addEventListner("click",function(evt){
evt.preventDefault();
},false);


<a href="http://www.google.com">Click here</a>
도움이 되었습니까?

해결책

Three problems :

  • getElementsByTagName must be called on the document or on an element
  • You can't add an event listener directly on the node list returned by getElementsByTagName, you must iterate over the elements it contains :
  • you have a typo in addEventListener

Here's a fixed code :

var avoidlink = document.getElementsByTagName("a");
for (var i=0; i<avoidlink.length; i++) {
  avoidlink[i].addEventListener("click",function(evt){
  evt.preventDefault();
  },false);
}

If you want to be able to attach an event listener to a node list, you may enrich NodeList.prototype :

NodeList.prototype.addEventListener = function(){
  for (var i=0; i<this.length; i++) {
      Element.prototype.addEventListener.apply(this[i] , arguments);
  }
}

Demonstration

Modifying the prototype of objects you don't own is generally frowned upon but this change is rather innocuous and natural.

다른 팁

Usually if many elements need the same event listener you can add the event listener to the container and filter out what element you would like to take action upon:

document.addEventListener("click",function(e){
  if(e.target,e.target.tagName.toLowerCase()==="a"){
    e.preventDefault();
  }
});

If you were to add extra anchor tags through script they will trigger the preventDefault too.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top