开发者

Code is not running on .click of hyperlink

开发者 https://www.devze.com 2022-12-27 04:43 出处:网络
Code is not running on .click when I h开发者_JAVA百科ave this: $(\".cancel\").click(function() { alert(\"got here\");

Code is not running on .click when I h开发者_JAVA百科ave this:

$(".cancel").click(function() {
    alert("got here");
    $(this).closest(":dialog").dialog("close");                            
});

<a class="cancel" href=""><img src="images/cancelButton.gif" border="0" /></a>

It's got to be something stupid, but I cannot see it.


I would assume you're wrapping the code in $(document).ready( function () { ... }); ?

$(document).ready( function () {
  $('.cancel').click( function(e) {
     alert('here!');
     e.preventDefault(); // prevents click from following through
  });
});


add return false at the end of your click event:

$(".cancel").click(function() {
    alert("got here");
    $(this).closest(":dialog").dialog("close");
    return false;                            
});


If href="" instead of href="#" doesn't that mean it actually reloads the page on click?


Anywhere you put an onclick event with a javascript call, if you add return false then the default behavior (what would have happened without the onclick event) will be disregarded.

And so in this case return return false will prevent the browser jump to the link anchor.

Edit

Fair comment below - looked at the jquery.com and it says

Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.


A couple of people have said add return false; to your click handler. You should instead use the preventDefault method on the event class like so:

$(".cancel").click(function(event) {
  event.preventDefault();
  alert("got here");
  $(this).closest(":dialog").dialog("close");
});

Make sure you pass in the event to the handler function. This is the preferred jQuery way. I also always put the preventDefault() as the first thing in the handler method, but I don't think that makes a difference.

0

精彩评论

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

关注公众号