jQuery code works in Firebug, but not on its own
I'm having quite the brainbuster of an issue right now. I am trying to change a link's hash tag at the end from "respond" to "comments" with jQuery. I have a simple script that should do this, however it does not work. The link does not change. However, Firebug shows no errors and when I run the code in Firebug's console, it works just as I intend.开发者_运维知识库 Why doesn't this work on its own? Does anybody have a solution, I'm at my wits edge with this one.
(function ($) {
$(document).ready(function() {
$("a[href$='respond']").each(function() {
$(this).attr("href", $(this).attr('href').replace("respond", "comments"));
});
});
})(jQuery.noConflict());
Thanks so much, I know this might be a pain to test but I'm really thankful.
Your code should be working fine, but your script tag is malformed. You have text/javscript
instead of text/javascript
. Also, you can optimize your code a little:
<script type="text/javascript">
jQuery(document).ready(function($){
$("a[href$='respond']").attr("href", function(index, attr){
return attr.replace("respond", "comments");
});
}).noConflict();
</script>
You're using $(document).load()
instead of $(document).ready()
.
(function ($) {
//---------------v
$(document).load(function() {
$("a[href$='respond']").each(function() {
$(this).attr("href", $(this).attr('href').replace("respond", "comments"));
});
});
})(jQuery.noConflict());
Why not just:
jQuery(function($) {
$("a[href$='respond']").each(function() {
$(this).attr("href", $(this).attr('href').replace("respond", "comments"));
});
});
If you pass a function to the jQuery constructor it adds it to the DOM Ready listeners and automatically passes itself as an argument.
精彩评论