在这里阅读后,我无法找到任何解释为什么这不起作用。 假设我得到了这个HTML:
<p lang="xx">bla bla bla bla</p>
<p lang="xy">yada yada yada</p>
<p lang="xx">bla bla bla bla</p>
<p lang="xy">yada yada yada</p>
<p lang="xx">bla bla bla bla</p>
<p lang="xy">yada yada yada</p>
<p lang="xx">bla bla bla bla</p>
<p lang="xy">yada yada yada</p>
我试图在语言属性之间切换。我想这样做:
<label for="language">Language:</label>
<input type="radio" name="language" value="xy" oninput="changeLanguage(this.value);" checked /> xy
<input type="radio" name="language" value="xx" oninput="changeLanguage(this.value);" /> xx
用CSS隐藏其中一种语言:
<style>
[lang=xx] { display: none;}
</style>
用JS切换:
<script>
var language = document.getElementsByName('language');
function changeLanguage(val) {
language.value = val;
if (val = "xx") {
document.write (
"<style>" +
"[lang=xx] {display: block;}" +
"[lang=xy] {display: none;}" +
"</style>");
}
if (val = "xy") {
document.write (
"<style>" +
"[lang=xy] {display: block;}" +
"[lang=xx] {display: none;}" +
"</style>");
}
}
</script>
它不起作用:点击单选按钮只是清空屏幕。我在这里缺少什么?
答案 0 :(得分:1)
document.write
无法为您正在尝试的工作而努力。为所有段落元素添加一个class属性:
<p class="langitem" lang="xx">bla bla bla bla</p>
<p class="langitem" lang="xy">yada yada yada</p>
<p class="langitem" lang="xx">bla bla bla bla</p>
<p class="langitem" lang="xy">yada yada yada</p>
<p class="langitem" lang="xx">bla bla bla bla</p>
<p class="langitem" lang="xy">yada yada yada</p>
<p class="langitem" lang="xx">bla bla bla bla</p>
<p class="langitem" lang="xy">yada yada yada</p>
然后将您的脚本变为:
<script>
var language = document.getElementsByName('language');
function changeLanguage(val) {
language.value = val;
var arr_elms = [];
arr_elms = document.getElementsByClassName("langitem");
for (var i = 0; i < arr_elms.length; i++) {
if(arr_elms[i].getAttribute("lang") == val)
arr_elms[i].style.display = 'block';
else
arr_elms[i].style.display = 'none';
}
}
</script>
这应该像你期望的那样有效。