简体   繁体   English

javascript 在 php foreach 中操作 html 元素

[英]javascript manipulating html elements in a php foreach

Consider the following:考虑以下:

<? php foreach($queryResult as $res) : ?>
    // output all table columns
    <form onsubmit="return javascriptFunction(); " method="post">
    <button id="b">edit</button>
    </form>
<?php endforeach; ?>

Obviously, when the javascript function is called, the id of the buttons are the same, so:很明显,当javascript函数被调用时,按钮的id是一样的,所以:

document.getElementById(b).value;

won't work as expected.不会按预期工作。 Is it possible to:是否有可能:

  • Give each button a unique id attribute while it is created in the loop?在循环中创建每个按钮时给它一个唯一的 id 属性?
  • Say I click the third button, is it possible for the javascript function to use that button that is clicked?假设我单击了第三个按钮,javascript 函数是否可以使用单击的那个按钮?

I absolutely have know idea how it can happen, looks like there's no way around it.我绝对知道它是如何发生的,看起来没有办法解决它。 Is this possible?这可能吗?

To give to each button a different id you can do this way:要给每个按钮一个不同的 id,你可以这样做:

<?php 
$i = 1; 
foreach($queryResult as $res) {  ?>
    // output all table columns
    <form onsubmit="return javascriptFunction(); " method="post">
    <button id="element-<?= $i ?>">edit</button>
    </form>
<?php $i++; } ?>

For the second question: if you want to pass the id of the button to javascriptFunction you can modify your code this way:对于第二个问题:如果你想将按钮的 id 传递给javascriptFunction你可以这样修改你的代码:

return javascriptFunction(<?= '\'element-'. $i . "'" ?>); 

and when javascriptFunction will be called, it will be passed the id of the button as the parameter and you could use it inside the functionjavascriptFunction被调用时,它会被传递按钮的 id 作为参数,你可以在函数内部使用它

You can use a forach and then you dont' have to keep track of the id iterator您可以使用forach ,然后您不必跟踪 id 迭代器

foreach($queryResult as $id=>$res) {  ?>
    // output all table columns
    <form onsubmit="return javascriptFunction(); " method="post">
    <button id="element-<?php echo $id ?>">edit</button>
    </form>
<?php $i++; } ?>

Also, FWIW, its of course terrible practice to have multiple elements with the same id, but document.querySelectorAll('#someID');此外,FWIW,它当然可怕的做法,具有相同的 id 的多个元素,但document.querySelectorAll('#someID'); will give you multiple elements in most browsers.将在大多数浏览器中为您提供多个元素。

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

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