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
Javascript Pass Element ID Attribute as Parameter
提问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/