javascript - 如何在 Javascript/jquery 中访问动态创建的 div 元素?
问题描述
这是我的代码。这里的主机名是一个数组。对于每个数组元素,我的循环将进行迭代。如果用户选择是,那么它应该显示 hideconf div 元素。如果不是,那么它应该隐藏元素。但仅对于第一次迭代它才有效。从第二次迭代开始,第一个 div 标签的元素开始显示和隐藏。问题出在身份证上。那么,我怎样才能实现我的目标。
<% hostname.forEach(function(data){ %>
<input class="form-control" id="fw" name="fwchange" type="radio" value="true" onclick="showconf()" /></label>
<input class="form-control" id="fw" name="fwchange" type="radio" value="true" onclick="noshowconf()" /></label>
<div class="hideconf" style="display:none">
<input type="text" class="form-control" id="fwchangedetail" name="fwchangedetail" placeholder="Configuration Change Details"/>
<input type="text" class="form-control" id="fwchangedetail1" name="fwchangedetail1" placeholder="Configuration Change Details"/>
<input type="text" class="form-control" id="fwchangedetail2" name="fwchangedetail2" placeholder="Configuration Change Details"/>
<input type="text" class="form-control" id="fwchangedetail3" name="fwchangedetail3" placeholder="Configuration Change Details"/></div>
<%}) %>
<script>
function showconf(){
document.getElementsByClassName('hideconf').style.display="block";}
function noshowconf(){
document.getElementsByClassName('hideconf').style.display="none";}
</script>
解决方案
试试这个好运:)
<% hostname.forEach(function(data, index){ %>
<input class="form-control" id="fw" name="fwchange" type="radio" value="true" onclick=`showconf(${index})` /></label>
<input class="form-control" id="fw" name="fwchange" type="radio" value="true" onclick=`noshowconf(${index})` /></label>
<div class="hideconf" style="display:none">
<input type="text" class="form-control" id="fwchangedetail" name="fwchangedetail" placeholder="Configuration Change Details"/>
<input type="text" class="form-control" id="fwchangedetail1" name="fwchangedetail1" placeholder="Configuration Change Details"/>
<input type="text" class="form-control" id="fwchangedetail2" name="fwchangedetail2" placeholder="Configuration Change Details"/>
<input type="text" class="form-control" id="fwchangedetail3" name="fwchangedetail3" placeholder="Configuration Change Details"/></div>
<%}) %>
<script>
function showconf(index){
document.getElementsByClassName('hideconf')[index].style.display="block";}
function noshowconf(index){
document.getElementsByClassName('hideconf')[index].style.display="none";}
</script>
=======更新=========
因为document.getElementsByClassName
返回一个 NodeList 数组。在您的函数中,您只是更改了第一个元素的样式。
// the index is the NodeList's index
document.getElementsByClassName('hideconf')[index].style.display
推荐阅读
- docker - How to install softwares and libraries inside windows based docker containers?
- java - Java Swing JEditorPane不输出空段落
- discord - 我正在制作一个 Discord Bot,它会向所有具有特定角色的用户发送消息,但是当我输入命令时它显示完成但没有 Dm 出现在用户面前
- c++ - UE4,C++,fscanf,用说明符匹配字符串
- sql - 如何插入到 postgres jsonb 列
- docker - VSCode docker dev 容器无法访问 ~/.ssh
- jquery - 替代 jQuery.html() 用于渲染局部视图
- java - 如何从位于 2 个字符之间的 char 数组中获取长度不确定的单词?
- odata - OData 元数据和 URI
- html - 无论如何要在 React 中的页面加载上进行输入自动对焦