简体   繁体   中英

Show content depending on domain using jQuery javascript

HI Guys I have a site that carries 2 domains one is .com and the other is a .us I am trying to get it to show a flag for the country domain chosen so if it is clicked on a link to direct to a .us I wanted to show the US flag:

I have made this so far but sometimes it works but sometimes not I have no idea why!

HTML:

<li>Currency <img class="usd-flag" style="display:none" src="/images/usd-flag.svg" width="20" height="14" alt="USD CURRENCY $;"/><img class="gbp-flag" style="display:none" src="/images/gbp-flag.svg" width="20" height="14" alt="GBP CURRENCY &pound;"/>
<ul>
<li><a href="http://www.example.com">BRITISH POUNDS ( &pound; ) </a></li>
<li><a href="http://www.example.us">US DOLLARS ( $ )</a></li>
</ul>
</li>

JS:

if(location.href.indexOf('.us') >= 0) {
        $('.usd-flag').show();
        $('.gbp-flag').hide();
    }
if(location.href.indexOf('.com') >= 0) {
        $('.gbp-flag').show();
        $('.usd-flag').hide();
    }//changes flag image depending on domain 

Can some one tells me whats wrong here plz?

Well of the top of my head I would recommend document.domain instead of location.href as it has a better output for parsing, but I think you just forgot the need to wait for the DOM to by ready before modifying it's elements. As you have tagged with jQuery you can use the below. Without it you will need a document event handler (which jQuery just wraps for you).

$(document).ready(function () {

    console.log(location.href)
    console.log(document.domain)

    if (location.href.indexOf('.us') >= 0) {
        $('.usd-flag').show();
        $('.gbp-flag').hide();
    }
    if (location.href.indexOf('.com') >= 0) {
        $('.gbp-flag').show();
        $('.usd-flag').hide();
    } //changes flag image depending on domain

});

FIDDLE

You could do this with a liquid if else statement and use contain.

{% if {{globals.site.host}} contains '.us' %}

<div>this is a .us domain</div>

{% else %} 

<div>This is a .com domain</div>

{% endif %}

OR you could use 2 if Statements as well. rather than the else depending on what you need.

Temporary Example here using AU domain.

http://liquiddev.rtweb.com.au/domain

Hope it helps!

您可以先将location.href.indexOf更改为location.href.toLowerCase()。indexOf,以便它将URL支持为.COM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM