Php JavaScript函数中唯一ID的变量
我有一个onclick事件,在PHPPhp JavaScript函数中唯一ID的变量,php,javascript,function,loops,onclick,Php,Javascript,Function,Loops,Onclick,我有一个onclick事件,在PHPforeach循环中调用,用于我需要单击其作者姓名的几个项目。只生成了一个名称,所以我知道每个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 f
foreach
循环中调用,用于我需要单击其作者姓名的几个项目。只生成了一个名称,所以我知道每个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 />';
?>
我陷入困境的是我的功能:
<script type="text/javascript">function setAuthor() {
var author = document.getElementById("closest").innerHTML;
window.alert(author);
document.forms["myform"].elements["author_name"].value = author; }</script>
<?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(){
var author=document.getElementById(“最近”).innerHTML;
window.alert(作者);
document.forms[“myform”].elements[“author_name”].value=author;}
如何在函数中为唯一ID创建一个变量,以便每个循环项生成不同的名称?一种方法是将此
传递给setAuthor函数:
<script type="text/javascript">function setAuthor() {
var author = document.getElementById("closest").innerHTML;
window.alert(author);
document.forms["myform"].elements["author_name"].value = author; }</script>
<?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/>";
?>
但是,不应该为每个元素设置onclick
inline和。您应该使用事件注册函数。代码中哪里有循环?您将生成closest1
,closest2
,等等,但查找最近的
对,我不知道如何将查找“closest1,closest2”写入函数只需单击onClick=“setAuthor(this)”
并将函数的签名更改为函数集作者(元素){
,然后执行var author=element.innerHTML
是的。但是它将每个名称输入到同一个输入元素中。我编辑了原始帖子,以显示每个作者都有一个与之关联的输入字段。我会在函数中添加一个计数器来分配函数吗?我错过了@outis的编辑,谢谢。我看到ID是g已传递,但作者值未找到输入字段的路径。是否需要更改输入字段的id?例如:;
我删除了$objkey周围的大括号,并将其替换为:id=“author\u name.'$objkey.”type=“text”name=“author\u name”value=“.”.$author.”/>';
这允许将名字保存到关联的输入字段中,但单击时,其他名称都不会填充任何输入。越来越近。Eureka!表单元素也需要唯一。我使用与表单id:echo“”的输入元素相同的方法;id在上述代码中生成。document.forms[“myform”+id].elements[“auth”+id].value=author;
感谢您的帮助