繁体   English   中英

如何在 Javascript/jquery 中访问动态创建的 div 元素?

[英]How to access dynamically created div elements in Javascript/ jquery?

这是我的代码。 这里的主机名是一个数组。 对于每个数组元素,我的循环将进行迭代。 如果用户选择是,那么它应该显示 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 数组。 在您的 function 中,您刚刚更改了第一个元素的样式。

// the index is the NodeList's index
document.getElementsByClassName('hideconf')[index].style.display

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM