首页 > 解决方案 > 如何在 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>

标签: javascripthtmljquerynode.js

解决方案


试试这个好运:)

<% 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

推荐阅读