简体   繁体   English

如何在动态创建元素的内联onclick事件中传递对象

[英]how to pass object in inline onclick event in dynamically creating elements

I am creating a table row dynamically. 我正在动态创建一个表行。 Each row is having onclick event. 每行都有onclick事件。 When I click on that table row I want to pass row object to a function but my problem is, while passing that object, I am getting [object object] string. 当我单击该表行时,我想将行对象传递给函数但我的问题是,在传递该对象时,我得到[object object]字符串。 So I am not able to use that object in function. 所以我无法在函数中使用该对象。

Please give some solution thanks in advance. 请提前感谢一些解决方案。

This is my code: 这是我的代码:

  var row;
  $.each(mydata, function(i,data){
            row+='<tr onclick="myfunction(\''+data+'\')"><td >data.name</td><td >data.age</td></tr>;
    });
 $("#myTable").append(row);

I would better use jQuery for defining click event handlers. 我最好使用jQuery来定义click事件处理程序。 Here is your updated code: 这是您更新的代码:

var $table = $("#myTable");
$.each(mydata, function(i,row){
        $tr = $('<tr>').appendTo($table);
        $tr.on("click", myfunction);
});

Convert the data object to the following style string. 将数据对象转换为以下样式字符串。

"{\"name\": \"lenient\", \"age\": 18}" 

Then bind it to the click event, you will get the object as the parameter inside the click function. 然后将其绑定到click事件,您将获得该对象作为click函数内的参数。

尝试添加JSON.stringify()

onclick="myfunction("+JSON.stringify(data) +")"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM