javascript - 如何检索文本内容并在复选框输入上显示
问题描述
我正在尝试构建一个小程序,您可以使用输入字段输入数据来构建一组包含列表项的无序列表。
我有一个复选框,当它被选中时,我希望它显示包含该文本位的整个无序列表,在本例中为亚特兰大。我希望将其余不包含此文本的无序列表设置为display: none;
for 循环是问题所在,尽管我已经玩了一整天并且无法按照我的意愿行事。
这是我认为有问题的代码:
checkboxInput.addEventListener('change', (e) => {
const isChecked = e.target.checked;
let ulList = document.getElementsByTagName('ul');
let liList = document.getElementsByTagName('li');
let locationList = document.getElementsByClassName('location');
if (isChecked) {
for (let i = 0; i < ulList.length; i += 1) {
for (let j = 0; j < liList.length; j += 1) {
let ul = ulList[i];
let li = liList[i];
if (li.textContent == 'atlanta') {
ul.style.display = '';
} else {
ul.style.display = 'none';
}
}
}
}
});
请在此处查看 jsFiddle 链接。
非常感谢任何帮助。
解决方案
我声明的几个变量在这段代码中是不必要的。liList
变量被替换为ulList.children
。第二个 for 循环也不是必需的。这是为实现我需要的功能而更改的 eventListener。
checkboxInput.addEventListener('change', (e) => {
const isChecked = e.target.checked;
let ulList = document.getElementsByTagName('ul');
if (isChecked) {
for (let i = 0; i < ulList.length; i += 1) {
let ul = ulList[i];
let liList = ul.children;
let li = liList[1];
if (li.textContent == 'atlanta') {
ul.style.display = 'block';
} else {
ul.style.display = 'none';
}
}
}
});
感谢Treehouse 的Kris对这个问题的解答。
推荐阅读
- primefaces - Primefaces 展示自动完成 countryService @inject 问题(Primefaces 8.0、JSF 2.3、TomEE-wepprofile)
- flutter - Flutter 初始状态 Cubit
- angular - 角材料垫菜单无法设置内部垫形式字段的样式
- c++ - 安全地将 int 重构为数组
- react-native - 全局安装 react-native 后,仍无法识别 react-native 命令
- java - WebServiceException:javax.net.ssl.SSLException:java.net.SocketException:连接重置
- .net - 当我关闭所选项目时,团队中的搜索扩展程序会显示“我们没有找到任何匹配项”消息
- ssh - Ansible 欢迎命令
- bigcommerce - 我想在页面帐户 Bigcommerce 中显示最近查看的产品
- java - 将 Spring Bean 暴露给 Micronaut 应用程序