html - change language using element.lang

2019-01-25 12:10发布

First question on stack, so hurray to me! I'm trying to develop a new way (apparently, since I've seen no solution to this online, perhaps cos it's not possible) to change the language of HTML written elements using JS and the lang property.

Basically, I have created multiple tags with the lang property in each of them, so that giving the certain lang a display value of -none-, hides it, and a value of -inherit- to show it. In that way, using the line:

a:lang(en),p:lang(en) { display : none }
a:lang(it),p:lang(it) { display : inherit }

I can see one language at a time. And that works!

Now, I have created an

<a href="" lang="en" id="en"> word </a>

tag around the english text, and the same with any other language with their own lang property. I have tried to use:

$("#en").click(function(){
           $('a:lang(en)').css('display', 'inherit');
           $('a:lang(it)').css('display', 'none');
           };

Which doesn't seem to work.

Any ideas?

Thanks a bunch, Shay

3条回答
贼婆χ
2楼-- · 2019-01-25 12:27

Have you close 'click' with ) ?

$("#en").click(function(){
       $('a:lang(en)').css('display', 'inherit');
       $('a:lang(it)').css('display', 'none');
 });
查看更多
smile是对你的礼貌
3楼-- · 2019-01-25 12:33

When load your page come with a <body class="it">, and all the :lang(en) tags will be hidden.

body.en :lang(it) {
  display: none;
}
body.it :lang(en) {
  display: none;
}

And when you need to change the language, simply change the className of <body>.

$("#en").click(function(){
  document.body.className = 'en';
};

Which is more elegant, and way faster.

demo: http://jsfiddle.net/Gw4eQ/


Use :not selector to make it work with more languages. demo

body:not(.en) :lang(en), 
body:not(.it) :lang(it), 
body:not(.fr) :lang(fr) { 
    display: none; 
}
查看更多
爷的心禁止访问
4楼-- · 2019-01-25 12:36

This is incorrect:

$('a:lang(en)').attr('display', 'inherit');
$('a:lang(it)').attr('display', 'none');

There is no attribute "display", instead use:

$('a:lang(en)').css('display', 'inherit');
$('a:lang(it)').css('display', 'none');

Or simply:

$('a:lang(en)').show();
$('a:lang(it)').hide();

...but you also have an error here where you didn't wrap your function correctly:

$("#en").click(function(){
    $('a:lang(en)').css('display', 'inherit');
    $('a:lang(it)').css('display', 'none');
}; // <---- error

Should be: });

$("#en").click(function(){
    $('a:lang(en)').css('display', 'inherit');
    $('a:lang(it)').css('display', 'none');
}); // <---- fixed

Also, I'd use inline rather than inherit. "inherit" does not mean "default", it means "inherit this property from the parent", which will probably be block. <a>'s default display is inline.

查看更多
登录 后发表回答