javascript 如何将对象传递给 onclick 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12501867/
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 16:22:00  来源:igfitidea点击:

How to pass an object to an onclick event

javascriptjquery

提问by noname

Possible Duplicate:
Event handlers inside a Javascript loop - need a closure?

可能的重复:
Javascript 循环内的事件处理程序 - 需要关闭吗?

I am getting some json object through an API call.It is of the folowing format:-

我通过 API 调用获取了一些 json 对象。它的格式如下:-

{data:[{id:"1",name:"some1",url:"someurl1"},{id:"2",name:"some2",url:"someurl2"}...]}

I get it through a jsonp result and it is parsed as below:-

我通过 jsonp 结果得到它,它被解析如下:-

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 
      }
    }
 }

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

我如何将特定对象从循环传递到 onclick 事件。我的意思是创建的第一个 div 应该有一个带有第一个对象数据的 onclick 事件,第二个 div 应该有来自第二个对象的数据..请问我是否需要更多说明

Edit:- If I do something like this:-

编辑:- 如果我这样做:-

item.onclick=function(){
  console.log(results.data[1])
}

I get that particular object in the onclick event of all the items , but that is not what i want

我在所有项目的 onclick 事件中得到了那个特定的对象,但这不是我想要的

Edit:- This is how i finally solved it. Thanks to the link pointed to by DCoder.

编辑:-这就是我最终解决的方法。感谢 DCoder 指向的链接。

item.onclick =function(object){
           return function(){
           //do something with the object
           }

         }(obj);

采纳答案by Shmiddty

Quick solution:

快速解决方案:

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
    }
}

回答by Craig MacGregor

You could always jQuery's datafunction to store and retrieve the data object:

你总是可以使用 jQuery 的data函数来存储和检索数据对象:

function(results){
  for(var i=0;i<10;i++){
    item=document.createElement("div");
    item.innerHTML=results.data[i].name;

    // Store object in data 
    $(item).data("results", results.data[i]);

    item.onclick=function(){
        // Retrieve the data needed
        var data = $(this).data("results");
        console.log(data);
      }
    }
 }

回答by Sujith Kp

Add a hidden field inside your div (created in loop), keep whatever you want in it. then on click of div. find hidden field inside it(div) and read its value.

在您的 div 中添加一个隐藏字段(在循环中创建),保留您想要的任何内容。然后点击div。在其中找到隐藏字段(div)并读取其值。

回答by Fabrício Matté

I'd personally use $.mapso the function callback creates a new execution context for each iteration.

我个人使用,$.map因此函数回调为每次迭代创建一个新的执行上下文。

As you've tagged the question with jQuery, your code can be as simple as

当您使用 jQuery 标记问题时,您的代码可以很简单

$($.map(data, function(v, i) {
    return $('<div>').html(data[i].name).click(function() {
        console.log(data[i]);
    });
})).appendTo('body'); //appending for demonstration purposes

Fiddle

小提琴

Of course, you have to wrap it inside a function and pass the dataarray of objects as you were doing previously.

当然,您必须将它包装在一个函数中并data像以前一样传递对象数组。

回答by Sujith Kp

The onclick event is fired from jquery when someone clicks on 'item'. You cannot expect custom data to the event handler unless it is triggered using trigger function.

当有人单击“项目”时,jquery 会触发 onclick 事件。除非使用触发器函数触发,否则您不能期望事件处理程序的自定义数据。

回答by Jamund Ferguson

You're running into trouble with doing async calls inside of js. This is a common problem and it's describe here: http://dojo-toolkit.33424.n3.nabble.com/Advice-on-closures-and-retaining-variable-values-inside-async-handlers-e-g-xhrGet-td3227726.html

您在 js 内部进行异步调用时遇到了麻烦。这是一个常见问题,在此处进行了描述:http: //dojo-toolkit.33424.n3.nabble.com/Advice-on-closures-and-retaining-variable-values-inside-async-handlers-eg-xhrGet- td3227726.html

Basically the value of iis equal to 9by the time your console.log is actually ran.

基本上,当您的 console.log 实际运行时,的值i等于9

There are many ways to solve this problem in general, but your specific solution should probably be to restructure things immensely. Consider this alternative (requires jQuery), but we could do the same without it very easily.

一般来说,有很多方法可以解决这个问题,但您的具体解决方案可能应该是极大地重组事物。考虑这个替代方案(需要 jQuery),但我们可以很容易地在没有它的情况下做同样的事情。

$.each(results, function(data) {
  var $el = $("<div></div>").html(data.name).click(function() { console.log(data) });
})

But it would be even better to use jQuery.data()to store things and then use .on()or .delegate()to listen for the click events like this

但是最好使用jQuery.data()来存储东西,然后使用.on().delegate()监听这样的点击事件

$.each(results, function(data) {
  var $el = $("<div></div>").addClass("yourThing").html(data.name).data("data", data);
})

// replace window with a closer parent if one exists
$(window).on("click", ".yourThing", function() {
   console.log($(this).data("data")); // retrieve data from jquerys .data() store
});