2014-04-06 100 views
0

我知道如何onclick事件没有参数添加到一个div:JS - 如何使用参数添加一个onclick事件到div?

newDiv.onclick = selectUnit; 

function selectUnit() {} 

但我不能使它与参数的工作原理:

function appendUnit(nb) { 
    var newDiv = document.createElement("div"); 

    newDiv.id = "unit" + nb; 
    newDiv.onclick = selectUnit(this.id); // This throws me undefined 
    document.getElementById("unitsList").appendChild(newDiv); 
} 

function selectUnit(id) { 
    console.debug(id); 
} 

我怎么能这样做?

+0

你可以指定何时调用appendUnit吗? – abc123

+0

'

Buy
'buyUnit()函数调用appendUnit()。 – Elfayer

回答

2

你需要为一个匿名函数,因为没有办法参数传递给引用功能

function appendUnit() { 
    var newDiv = document.createElement("div"); 

    newDiv.onclick = function() { 
     selectUnit(this.id); 
    } 

    document.getElementById("unitsList").appendChild(newDiv); 
} 

function selectUnit(id) { 
    console.debug(id); 
} 

但要注意的this值将保持,所以你可以做

function appendUnit() { 
    var newDiv = document.createElement("div"); 

    newDiv.onclick = selectUnit; 

    document.getElementById("unitsList").appendChild(newDiv); 
} 

function selectUnit() { 
    console.debug(this.id); // this is still the same here 
} 
0

你从来没有设置ID在你的示例代码:

function appendUnit() { 
    var newDiv = document.createElement("div"); 
    newDiv.id = "somevalue"; 

    [...] 
    newDiv.onclick = "selectUnit(this.id);" // This throws me undefined 
    document.getElementById("unitsList").appendChild(newDiv); 
} 

function selectUnit(id) { 
    console.debug(id); 
} 
+0

我在真实的代码中做了编辑我的文章。但是你的代码不起作用。你指出了这个问题,'this'指的是此时不是div的函数。我不知道如何解决这个问题。 – Elfayer

+0

尝试在onclick事件中添加引号。我刚编辑过这个例子。 – tekrat

0

试试这个

function appendUnit() { 
    var newDiv = document.createElement("div"); 

    [...] 
    newDiv.onclick = function(){ 
     selectUnit(newDiv.id); // This throws me undefined 
    } 
    document.getElementById("unitsList").appendChild(newDiv); 
} 
1

随着该行代码

newDiv.onclick = selectUnit(this.id); 

你只需要调用该函数,得到它的结果,并将其存储到onclick处理程序。

没有定义内部返回的函数返回undefined。 this.id将引用您当前在您的范围内的this元素,该元素可能是window对象。

当的onclick发生时,地方铬会调用这个函数

DOMElement.onclick(EventObject); 

并伴您行会是这样的

(undefined)(this.id); 

导致错误

所有你必须要做的就是用方法设置onclick

newDiv.onclick = selectUnit; 

和Chrome将调用此

DOMElement.onclick(EventObject); 

DOMElement.onclick == selectUnit我们可以假设的代码上线是与此类似:

selectUnit(EventObject); 

然后在你的selectUnit功能,你必须知道如何访问id 。你可以在https://developer.mozilla.org/en-US/docs/Web/API/Event看到你可以用它做什么。所以新的selectUnit函数将是:

function selectUnit(event) { 
    var id = event.target.id; 
    console.debug(id); 
} 
相关问题