在这里阅读后,我找不到任何解释为什么这行不通。
假设我得到了以下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>
这是行不通的:单击单选按钮只会清空屏幕。我在这里想念什么?
最佳答案
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>
那应该如您期望的那样工作。