【问题标题】:Multiple Button have inside foreach loop but only first button can be clickable. How to make all the buttons can click?多个按钮有内部 foreach 循环,但只有第一个按钮可以点击。如何让所有的按钮都能点击?
【发布时间】:2017-06-22 09:19:56
【问题描述】:
<? foreach(.........){                      

<select id = "RelationshipSelect" name = 'RelationshipSelect' disabled>
                                //some codes implement                                                          
                        </select>`enter code here`

                        <input type = 'text' value = "<? echo ... ?>" id = "affectedSystems_0" name = 'affectedSystems_0' readonly> 

                                    <input type = "button" id = 'findAffectedSystems_0' value = 'Find' disabled>
                                        <input type = "button" id = 'removeAffectedSystems_0' value = 'Remove' disabled>


        <?}?>   

as showing in the photo, CI Relationship Field data are retrieve using foreach loop.

在 javascript 文件中,我将“findAffectedSystems_0”称为查找按钮 ID,但它仅适用于“查找”按钮的第一行。我应该怎么做才能让所有的按钮都可以点击。

document.getElementById("findAffectedSystems_0").addEventListener("click", function (){
              //some codes work

});

【问题讨论】:

  • 使按钮的 ID 唯一。
  • 查找和删除按钮不能有相同的id。你需要让它像 findAffectedSystems_0findAffectedSystems_1 一样动态化
  • 谢谢@JigarShah。但是我如何在循环中获取按钮的动态 id。请帮助我,我是这方面的新手
  • 不!为所有按钮分配一个类,例如class="btn",然后使用 document.getElementsByClassName
  • @A.S 我已经添加了示例代码。

标签: javascript php foreach


【解决方案1】:

你应该这样做

foreach ($variable as $key => $value) { // $variable should be array
        ?>
        <input type="button" class="common-class" name="findAffectedSystems_<?php echo $key ?>" id="findAffectedSystems_<?php echo $key ?>">
        <input type="button" class="common-class" name="removeAffectedSystems_<?php echo $key ?>" id="removeAffectedSystems_<?php echo $key ?>">
        <?php
    }

如果您需要对每个 btn 进行单独操作,则使用 id 属性,否则对于常见操作,您应该使用类属性

【讨论】:

  • 很高兴为您提供帮助:)
  • @P.Som 如果您觉得这很有用,请接受一个答案,以便可以关闭问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2014-05-12
  • 2014-08-17
  • 2020-04-13
相关资源
最近更新 更多