jQuery.click <a href="#">

时间:2018-12-09 09:09:26

标签: jquery javascript-events

I am trying to add a click event to an a element with a href of # e.g. <a href="#">Blah!</a>


    jQuery('a').click(function() {
        event.preventDefault();
        console.log('clicked!');
    });

This works for every a except those with href="#".

Any help would be highly appreciated. Thanks!

EDIT: Not working in any browser in Windows.

jQuery('a').click(function() {
  event.preventDefault();
  console.log('clicked!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">Blah!</a>

2 个答案:

答案 0 :(得分:0)

如何使用这样的东西:

jQuery('a').click(function(e)  { 
   if($(this).attr("href") == "#"){
      e.preventDefault();
      console.log("clicked");
   }
});

或使用类似这样的内容:

jQuery('a[href$="#"]').click(function(e) { 
   e.preventDefault();     
   console.log("clicked"); 
});

答案 1 :(得分:0)

正如@CertainPerformance所说的那样,您忘记将事件处理程序作为参数传递给函数了,只需从

更改代码即可
jQuery('a').click(function() {
  event.preventDefault();
  console.log('clicked!');
});

jQuery('a').click(function(event) {
  event.preventDefault();
  console.log('clicked!');
});