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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14187322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:57:14  来源:igfitidea点击:

Javascript Pass Element ID Attribute as Parameter

javascriptonclickparameter-passingsetattribute

提问by DVCITIS

This statement works. On the click of the node, i get a message displaying its ID.

此语句有效。单击该节点时,我会收到一条显示其 ID 的消息。

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

I need to pass the value of this.idto a different function and am struggling to get around it.

我需要将this.id的值传递给不同的函数,并且正在努力解决它。

Attempt 1:

尝试 1:

The below does not work; I understand that i cant pass this.idto another function, which does the same thing, because thisis not relevant to anything within the test function:

以下不起作用; 我知道我不能将this.id传递给另一个执行相同操作的函数,因为与测试函数中的任何内容都不相关:

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

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

Attempt 2:

尝试 2:

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

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

Why is testvarnot recognised in my setAttribute line?

为什么在我的 setAttribute 行中无法识别testvar

回答by Kevin Bowersox

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

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

Example: http://jsfiddle.net/sHZeL/1/

示例:http: //jsfiddle.net/sHZeL/1/