开发者

e.preventDefault() is not behaving correctly

I have a drop down menu that is still triggering an href change even though I'm calling e.preventDefault(). This is how I have my jquery address change configured:

$(document).ready(function() {

    // Setup jQuery address on some elements
    $('a').address();

    // Run some code on initial load
    $.address.init(function(e) {
        // Address details can be found in the event object
    });

    // Handle handle change events
    $.address.change(function(e) {

        var urlAux = e.value.split('=');
        var page   = urlAux[0];
        var arg  = urlAux[1];

        ....
     });
});

My drop down id looks like this:

<li id="search"><a href="#" class="drop" >Search</a>

my event handler for the drop down is below:

      $('#search').click(function(e) {
          e.preventDefault();
          $(this).children(menuItemChildren).slideDown(0);
          $(this).hover(function() {
          }, function(){    
              $(this).children(menuItemChildren).slideUp(0);
          });
      });

Even though I'm calling e.preventDefault() on m开发者_开发知识库y #search element it still triggers an address change. Any idea whats wrong?


This should work

<li id="search"><a href="javascript:void(0)" class="drop" >Search</a>


You should add a click handler on the a element, with a call to e.preventDefault()

$('#search a.drop').click(function(e) {
      e.preventDefault();
  });


Events bubble upwards, from child to parent. You're trying to prevent the default action on the <a> by calling e.preventDefault(); on the parent <li>. The problem is that all actions connected with the <a> will fire before those connected to the <li> because of the event bubbling order I described in the first sentence. In other words, e.preventDefault(); doesn't get called until after the event has already been triggered on the child.

You should bind a click event to the <a> element, and call e.preventDefault(); from there.


The problem is most likely that MouseEvent e does not reference the a tag because you're binding the click event to the list element. You can check that using console.log(e.target). You may see that e.target is a list element. You can fix that by binding another event to

$('#search a').click(function (e) {
  e.preventDefault();
});

But why use e.preventDefault() when you can just remove the href attribute? Do this and there will be no action taken upon click.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜