Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.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_Onclick_Parameter Passing_Setattribute - Fatal编程技术网

Javascript将元素ID属性作为参数传递

Javascript将元素ID属性作为参数传递,javascript,onclick,parameter-passing,setattribute,Javascript,Onclick,Parameter Passing,Setattribute,这句话很管用。单击节点时,我会收到一条显示其ID的消息 newnode.setAttribute("onClick", "alert(this.id)"); 我需要将this.id的值传递给另一个函数,我正在努力绕过它 尝试1: 下面的选项不起作用;我理解,我不能将此.id传递给另一个函数,该函数执行相同的操作,因为此与测试函数中的任何内容无关: newnode.setAttribute("onClick", "test(this.id)"); function test(f){ al

这句话很管用。单击节点时,我会收到一条显示其ID的消息

 newnode.setAttribute("onClick", "alert(this.id)"); 
我需要将this.id的值传递给另一个函数,我正在努力绕过它

尝试1:

下面的选项不起作用;我理解,我不能将此.id传递给另一个函数,该函数执行相同的操作,因为与测试函数中的任何内容无关:

newnode.setAttribute("onClick", "test(this.id)"); 

function test(f){
alert(f);
}
尝试2:

var testvar = newnode.id;
newnode.setAttribute("onClick", "test(testvar)"); 

function test(f){
alert(f);
}
为什么在我的setAttribute行中无法识别testvar

newNode.onclick = function(){
  test(this.id);
};

function test(id){
  alert(id);
}

示例:

如果
alert(this.id)
有效,那么
test(this.id)
将有效-
alert()
只是一个函数。请小心字符串中的函数,因为您在那里触发
eval
,这在99%的时间里是不必要的。请尝试以下操作:
newnode.setAttribute(“onClick”,test(testvar))另外,将单击事件指定为属性不是一个好主意。只需使用
addEventListener
el.onclick=fn
。还要注意,
onclick
通常都是小写的。