Jquery attr href, why doesn't it work?

I thought the following line of code should work fine: $(".1").attr('href', '#Home'); Right?

But why doesn't this work when I integrate it with another jQuery script?

 $(window).bind("load", function() { $('.1').click(function() { $('.1').removeClass('tab1'); $('.2').removeClass('active2'); $('.3').removeClass('active3'); $('.4').removeClass('active4'); $('.1').addClass('active1'); $('.2').addClass('tab2'); $('.3').addClass('tab3'); $('.4').addClass('tab4'); $('#PortfolioMainContainer:visible').fadeOut("slow",function(){ $('#TextContent').load('Home.html', function() { $(this).fadeIn("slow") }); return false; }); if(!$(".1").hasClass("ActiveTab1")) { $(".1").attr('href', '#Home'); $('#TextContent:visible').fadeOut("slow",function(){ $('#TextContent').load('Home.html', function() { $(this).fadeIn("slow") }); return false; }); } $(".1").addClass("ActiveTab1"); $(".2").removeClass("ActiveTab2"); $(".3").removeClass("ActiveTab3"); $(".4").removeClass("ActiveTab4"); }); }); 

What I want to get is when you click on the div with class .1, then the URL should be changed to http://www.websiteurl.com/#Home

Does anyone have an idea how to make it work?

+4
source share
5 answers

I tested the following statements and it really works.

  $(function() { $("a").attr("href", "#123"); }); 

And if I click on any link, then the place actually attached # 123 at the end is without a doubt.

I think your problem may be, your ".1" is not attached to the binding object. In the HTML specification, only the hyperlink (and some inappropriate html tags) have the "href" attribute. This means, for example, that your .1 is actually <div class='.1'> , then even you put the href attribute on it, it would not have the default behavior acting as a "hyperlink". In this case, you should programmatically navigate to the specified URL, for example:

 $(".1").click(function(){ window.location = "current/url" + "#home"; }); 
+6
source

You can use document.URL to get the current location, so

 $(".1").attr('href', document.URL + '#Home'); 

The thing is, document.URL will get the URL with pounds and everything, so if you are on example.com/#work, docuement.URL will return "example.com/#work". So you can do some validation, or if you know that you are on a static url for this script, you can just copy the url.

One more thing, I see that you add the ActiveTab1 class after checking for it, so it should not go into this part of the code if it does not already have this class.

+3
source

You must add the current location to the href attribute.

0
source

You need to add the namespace $ ("a"). attr ("xlink: href", "# 123");

0
source

If your tag is in an iframe, you can’t do anything by jquery; try to do something like this console.log ($ (". 1"). Html ()); and you will see null

0
source

All Articles