我正在尝试为网站实现多语言支持,为此我需要选择所有具有$(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);
});
});
});
属性的元素。这就是我的Js代码的样子
<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>
这是我试图测试出来的HTML代码
Byte[]
我对jquery选择器感到困惑,实际上不知道如何使用它们。任何帮助将不胜感激
答案 0 :(得分:2)
要获取具有指定类名的所有元素,请尝试document.getElementsByClassName: -
var x = document.getElementsByClassName("className");
Internet Explorer 8及更早版本不支持getElementsByClassName()
方法。
function myFunction() {
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!";
x[1].innerHTML = "my first code snippet"
}
&#13;
<div class="example">First div element with class="example".</div>
<div class="example">Second div element with class="example".</div>
<button onclick="myFunction()">Try it</button>
&#13;
答案 1 :(得分:1)
这应该可以解决问题:
$(".lang").each(function() {
const $lang = $(this);
// translate this item's text
});