开发者

Why can't I control the click event of this link with jQuery?

I know jQuery pretty we开发者_运维知识库ll. This one is driving me nuts because it's SO simple.

I have this in the <head>:

<script>
$(document).ready(function() {
    $(".delete_social").click(function() {
        return false;
    });
});
</script>

and in the body I have a series of links:

<a class="delete_social" href="save_page.php?delete_social=true">Delete</a>

But EVERY time I click those links, it takes me right ot that PHP page. Why isn't jQuery intercepting the click? Any theories?

PS I've tried adding a simple alert() event to the click() function, with no change, and I've tried using "a.delete_social" in the jQuery $() call. Neither worked.


If these links are loaded in dynamically, you'll need to use $.live() to control them:

$(".delete_social").live("click", function(e){
  e.preventDefault();
  // do stuff
});

$.live() causes dynamically-added elements to adhere to previously-declared rules.


Try this to prevent the URL from loading:

$(".delete_social").click(function(e) {
    e.preventDefault();
    return false;
});

Also, you should be getting an alert and other code to run inside the click handler. If it's not, then something else on the page is causing something weird to occur.


Here's a couple of questions I'd ask while debugging:

  • Are you sure the click event is being attached to the anchors?
    • Try moving your script take to the bottom of the page and attaching the click events without using the ready function.
  • Is $(".delete_social").length greater than 0?
  • Are there any JavaScript errors when I load the page?
  • Is jQuery loading correctly?
    • Does $.fn.jquery return the current version of jquery you're using?
  • Consider using event.preventDefault(); instead.


Try this:

<script>
$(document).ready(function() {
    $(".delete_social").click(function(event) {
        event.preventDefault();
    });
});
</script>


Check the rest of your javascript. return false; or .preventDefault(); should do the trick. If they're not working, it usually means there's an error somewhere else in your js, and your browser never gets to that line of code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜