gpt4 book ai didi

javascript - 按类隐藏元素(仅限 Javascript,无 Jquery)

转载 作者:行者123 更新时间:2023-11-28 01:10:18 25 4
gpt4 key购买 nike

我想按类名隐藏元素。我找到了一个在函数之外运行的工作示例。但是,当我使用 onClick 时,它似乎不再起作用。请看以下示例:http://jsfiddle.net/SkfDz/9/有人可以帮我吗?

HTML:

<input class="" name="options" id="opt1" type="radio" onClick="hideToday()"/><label for="opt1">Hide today</label>
<input class="" name="options" id="opt1" type="radio" onClick="hideToday()"/><label for="opt1">Hide today</label>

<div class="today">TODAY</div>
<div class="today">TODAY</div>
<div class="today">TODAY</div>

<div class="tomorrow">TOMORROW</div>

脚本:

function hideToday() {
var todayElements = document.getElementsByClassName('today'), i;
for (i = 0; i < todayElements.length; i += 1) {
todayElements[i].style.display = 'none';
};
};

var tomorrowElements = document.getElementsByClassName('tomorrow'), i;
for (i = 0; i < tomorrowElements.length; i += 1) {
tomorrowElements[i].style.display = 'none';
}

最佳答案

它在 jsfiddle 中不起作用的原因是您的 hideToday 函数超出了范围。我不知道 jsfiddle 中的脚本存在哪个范围,但它似乎不是全局的。

如果您将相同的代码放入网页中并查看它,它会按预期工作:

<html>
<body>
<input class="" name="options" id="opt1" type="radio" onClick="hideToday()"/><label for="opt1">Hide today</label>
<input class="" name="options" id="opt1" type="radio" onClick="hideToday()"/><label for="opt1">Hide today</label>
<br>
<br>
<div class="today">TODAY</div>
<div class="today">TODAY</div>
<div class="today">TODAY</div>
<br>
<div class="tomorrow">TOMORROW</div>
<script>
function hideToday() {
var todayElements = document.getElementsByClassName('today'), i;
for (i = 0; i < todayElements.length; i += 1) {
todayElements[i].style.display = 'none';
};
};

var appBanners = document.getElementsByClassName('tomorrow'), i;
for (i = 0; i < appBanners.length; i += 1) {
appBanners[i].style.display = 'none';
}
</script>
</body>
</html>

您可以通过将 hideToday 导出到 window 来修复 fiddle :

window["hideToday"] = hideToday;

http://jsfiddle.net/SkfDz/16/

关于javascript - 按类隐藏元素(仅限 Javascript,无 Jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24531977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com