Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
未通过函数调用JavaScript传递Id_Javascript_Dom - Fatal编程技术网

未通过函数调用JavaScript传递Id

未通过函数调用JavaScript传递Id,javascript,dom,Javascript,Dom,我在工作时有一个服务器为我们内部网上的一个特殊页面提供密码保险库,但我在通过edit()函数将ID传递到脚本中时遇到问题。以下是适用的标记(如您所见,它包含在PHP数组中。所有内容,包括id都被正确地提供(即源代码处的id将读取n1或p7等): 很明显,ID没有正确通过,但我不知道该怎么办。我也尝试过将ID“硬编码”到onclick中的函数中,如下所示:edit(n$OTHERInfo[0]),但我也遇到了同样的问题。IDatedit函数是对单击元素的引用 onclick='edit(this.

我在工作时有一个服务器为我们内部网上的一个特殊页面提供密码保险库,但我在通过
edit()
函数将ID传递到脚本中时遇到问题。以下是适用的标记(如您所见,它包含在
PHP
数组中。所有内容,包括
id
都被正确地提供(即源代码处的id将读取
n1
p7
等):


很明显,ID没有正确通过,但我不知道该怎么办。我也尝试过将ID“硬编码”到
onclick
中的函数中,如下所示:
edit(n$OTHERInfo[0])
,但我也遇到了同样的问题。

ID
at
edit
函数是对单击元素的引用

onclick='edit(this.id)'


“this”是整个
元素,而不仅仅是它的id,因此您的脚本应该是:

<script>
function edit(element){
    element.style.backgroundColor = "white";
    element.style.color = "black";
    element.setAttribute("contentEditable", "true");
} 
</script>

功能编辑(元素){
element.style.backgroundColor=“白色”;
element.style.color=“黑色”;
setAttribute(“contentEditable”、“true”);
} 

您提供的是
编辑(此)
。关键字
引用实际元素。它不引用元素的ID。您可以在不使用
document.getElementById
的情况下修改代码

function edit(element) {
    element.style.backgroundColor = "white";
    element.style.color = "black";
    element.setAttribute("contentEditable", "true");
}
$OTHERInfo[1]
如果将
传递给
编辑
函数,则将使用整个元素(即
元素)作为参数,而不是其id


您可以尝试
onclick='edit(this.id)
。这将为您提供
元素的id作为参数。

我认为
edit(This)
发送的不仅仅是id,而是整个对象。因此,尝试执行
document.getElementById(id.id).style…
看看这是否有帮助?改用这个document.getElementById(id)@AdamMcGurk别担心!下面来自CodeConfident的答案应该做同样的工作,可能也是一种更干净的方法(因为你不必再次查找元素),所以试试吧!(编辑:CynePhoba回复得更快!)…是的,最好用id替换document.getElementById(id.id),因为您已经有了元素。调试提示。检查您是否得到有效输入总是很好的,即
如果(id==null)
控制台。记录
您的对象以确保您的对象是您认为的对象谢谢!我喜欢这个答案的干净!我会尽快接受的哈哈
onclick='edit(this.id)'
function edit(id){
  id.style.backgroundColor = "white";
  id.style.color = "black";
  id.setAttribute("contentEditable", "true");
} 
<script>
function edit(element){
    element.style.backgroundColor = "white";
    element.style.color = "black";
    element.setAttribute("contentEditable", "true");
} 
</script>
function edit(element) {
    element.style.backgroundColor = "white";
    element.style.color = "black";
    element.setAttribute("contentEditable", "true");
}
<td id='n$OTHERInfo[0]' onclick='edit(this)' contentEditable='false'>$OTHERInfo[1]</td>