JavaScript函数中唯一ID的变量


Variable for unique ids in JavaScript function

我在PHP foreach循环中调用了一个onclick事件,用于我需要单击其作者名称的几个项目。只生成了一个名称,所以我知道每个HTML元素都必须有一个唯一的id。我已经有了一个用于循环中使用的计数器的变量$objkey,所以我将其附加到id中。

<?php
//This is the item that appears in the loop. 
//Currently, clicking on each one that is generated only generates the first author name
//The correct author as passed by PHP displays in the loop.
//$closest is the value of the author's name.
echo 'Click name to add <span><button id="closest' . $objkey . '"  onClick="setAuthor()">' . $closest . '</button></span><br />';
?>

我已经做了一个print_r('$objkey);,计数器的适当值正在传递。

我希望将此按钮元素$closest的值传递给输入字段。我已经将变量附加到输入的id和name元素中(不确定这是否有帮助)(UPDATE:每个作者都有一个输入字段需要获取值):

<?php 
echo '<input id="author_name' . $objkey . '"  type="text" name="author_name' . $objkey .  '" value="' . $author . '" />'; 
?>

我陷入困境的是我的功能:

<script type="text/javascript">function setAuthor() {
var author = document.getElementById("closest").innerHTML;
window.alert(author);
document.forms["myform"].elements["author_name"].value = author; }</script>

如何在函数中为唯一id创建一个变量,以便每个循环项生成不同的名称?

一种方法是将this传递给setAuthor函数:

<?php
//This is the item that appears in the loop. 
//Currently, clicking on each one that is generated only generates the first author name
//The correct author as passed by PHP displays in the loop.
//$closest is the value of the author's name.
echo "Click name to add <button id='closest_{$objkey}' onClick='setAuthor(this)'>{$closest}</button><br/>";
?>

使用这种方法,您可以访问setAuthor:中的元素

<script type="text/javascript">
function setAuthor(el) {
    var author = el.innerHTML,
        id = el.id.replace(/^closest_/, '');
    if (console) {
        console.log(author);
    }
    document.forms["myform"].elements["author_name_" + id].value = author;
}
</script>

但是,不应该为每个元素设置内联和onclick。您应该使用事件注册功能。