我正在尝试为网站实现多语言支持,为此我需要选择所有具有class="lang"
属性的元素。这是我的Js代码:
$(function(){
var language = localStorage.getItem('language');
if(language !== null){
//this does not work
$(document).find('.lang').each(function (index, element) {
if($(this).attr('placeholder')!=null){
//change placeholder text
}
$(this).text(arrLang[language][$(this).attr('key')]);
});
}
//this works
$(document).on('click','.translate',function () {
var lang = $(this).attr('id');
$(document).find('.lang').each(function (index, element) {
if($(this).attr('placeholder')!=null){
//change placeholder text
}
$(this).text(arrLang[lang][$(this).attr('key')]);
localStorage.setItem('language',lang);
});
});
});
这是我要测试的 HTML 代码:
<div class="navbar navbar-default navbar-static-top">
<div class="container-fluid">
<div class="navbar-header">
<div class="navbar-brand">
<img alt="brand" src="../img/th-logo.png" height="25px" width="60px" href="Startsite.jsp">
</div>
</div>
<div class="navbar-brand">Studienlaufplan </div>
<button class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="collapse navbar-collapse navHeaderCollapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="../Startsite.jsp" class="lang" key="tasks" >Aufgaben</a> </li>
<li><a href="../Account.jsp" class="lang" key="account" >Konto</a> </li>
<li><a href="Canal.jsp" class="lang" key="cannals">Kanäle</a> </li>
<li><a href="Settings.jsp" class="lang" key="settings">Einstellugen</a> </li>
<li class="dropdown">
<a href="#" class="lang dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" key="language">Sprache</a>
<ul class="dropdown-menu">
<li><a href="#" class="translate" id="de">Deutsch</a></li>
<li><a href="#" class="translate" id="en">English</a></li>
</ul>
</li>
<li><a href="/Controller/Logout" class="lang" key="logout">Abmelden</a></li>
</ul>
</div>
</div>
</div>
我对jQuery选择器感到困惑,实际上也不太会很好地使用它们。任何帮助都将不胜感激。
data-key
代替key
。 - BarmarlocalStorage
中吗? - Barmar