问题描述
我通过API调用得到了一些json对象。它具有以下格式: -
I am getting some json object through an API call.It is of the folowing format:-
{data:[{id:"1",name:"some1",url:"someurl1"},{id:"2",name:"some2",url:"someurl2"}...]}
我通过jsonp结果得到它并解析如下: -
I get it through a jsonp result and it is parsed as below:-
function(results){
for(var i=0;i<10;i++){
item=document.createElement("div");
item.innerHTML=results.data[i].name;
item.onclick=function(){
console.log(results.data[i]); //--->this is where i am stuck
}
}
}
如何将特定对象从循环传递给onclick事件。我的意思是创建的第一个div应该有一个带有第一个对象数据的onclick事件,第二个div应该有来自第二个对象的数据..
请问我是否需要进一步澄清
How do i pass the particular object from the loop to the onclick event. I mean the first div created should have an onclick event with the data of the first object and the second div should have the data from the second object..Please ask me if any more clarification is required
编辑: -
如果我这样做: -
-If I do something like this:-
item.onclick=function(){
console.log(results.data[1])
}
我在所有项目的onclick事件中得到该特定对象,但这不是我想要的
I get that particular object in the onclick event of all the items , but that is not what i want
编辑: -
这个是我最终如何解决它。感谢DCoder指向的链接。
-This is how i finally solved it. Thanks to the link pointed to by DCoder.
item.onclick =function(object){
return function(){
//do something with the object
}
}(obj);
推荐答案
快速解决方案:
function(results){
for(var i=0;i<10;i++){
(function(index){ // create a closure, this makes a new scope
item=document.createElement("div");
item.innerHTML=results.data[index].name;
item.onclick=function(){
console.log(results.data[index]); //--->this is where i am stuck
}
})(i); // pass in i
}
}
这篇关于如何将对象传递给onclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!