开发者

jQuery code not executing when DOM is ready

I have written a simple jQuery script that changes the hash tag of a link. I do this because I am using IntenseDebate comments in Wordpress but the comment link still links replaced id of the old comments. I'm using jQuery so that if javascript is enabled, the user can click on the comments link and it will take them to the IntenseDebate comments. If its not enabled it will take them to the traditional comments (because IntenseDebate requires javascript to function).

The issue I'm having lies in this script to change the hash tag at the end of the link. Currently the URL "someurl.com/#respond" but I need the script to change it to "someurl.com/#comments". What is happening is that the script doesn't work, however I believe my syntax is correct so I decided to try copying and pasting the code into Firebug's console and the code executed perfectly. I could see that the link I was trying to change was now correct, and I could click on it and it worked as I desired. So what I don't understand is why the code is not executing when it is supposed to. I am using $(document).ready() and I have other jQuery on the page that executes just fine. I even tested it on a simple HTML page away from all the problems that might be caused by Wordpress and I received the same result. Does anyone know why this might be happening?

Here is my code (I am using noConflict because Wordpress makes use of other frameworks):

jQuery.noConflict();
jQuery(document).ready(function($) {
$("a[href开发者_如何学Go$='respond']").each(function() { 
    this.href = this.href.replace("respond", "comments");
});
})(jQuery);

Thanks very much for your help!


You are invoking the result of jQuery(document).ready() that will give you a type error, you are looking for this pattern:

(function ($) { 
  // inside this function, you can use `$`
  $(document).ready(function() {
    $("a[href$='respond']").each(function() { 
      this.href = this.href.replace("respond", "comments");
    });
  });
})(jQuery.noConflict());

In the above code you declare an anonymous function that is immediately invoked, passing the result of jQuery.noConflict() as the $ argument to that function.


You needn't pass arguments when invoking .ready(). jQuery passes the jQuery object as the initial param when it calls your function.

jQuery.noConflict();
jQuery(document).ready(function($) {
    $("a[href$='respond']").each(function() { 
        this.href = this.href.replace("respond", "comments");
    });
});

http://api.jquery.com/ready/


The inner line should be:

jQuery.noConflict();
jQuery(document).ready(function($) {
    $("a[href$='respond']").each(function() { 
        $(this).attr("href", $(this).attr('href').replace("respond", "comments"));
    });
});

The browser doesn't like casting replace directly on this.href;

Edit:or maybe it was just my browser having a hissy.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜