【问题标题】:Javascript Pass Element ID Attribute as ParameterJavascript 将元素 ID 属性作为参数传递
【发布时间】:2012-12-20 16:09:10
【问题描述】:

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

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

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

尝试 1:

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

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

【问题讨论】:

  • 如果alert(this.id) 有效,那么test(this.id) 将有效 - alert() 只是一个函数。
  • 小心字符串中的函数,因为你在那里触发了eval,这在 99% 的情况下都是不必要的。
  • 试试这个:newnode.setAttribute("onClick", test(testvar));
  • 另外,将点击事件分配为属性并不是一个好主意。只需使用addEventListenerel.onclick = fn。还要注意onclick 通常都是小写的。

标签: javascript onclick parameter-passing setattribute


【解决方案1】:
newNode.onclick = function(){
  test(this.id);
};

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 2016-11-18
    相关资源
    最近更新 更多