简体   繁体   English

javascript:将对象作为参数传递给字符串内的 onclick 函数

[英]javascript: pass an object as the argument to a onclick function inside string

I would like to pass an object as parameter to an Onclick function inside a string.我想将一个对象作为参数传递给字符串内的 Onclick 函数。 Something like follwing:类似于以下内容:

function myfunction(obj,parentobj){ 
   var o=document.createElement("div");
   o.innerHTML='<input type="button" onclick="somelistener(' + obj + ')" />';
   parentobj.appendChild(o.firstChild);
}

Obviously, this doesn't work.显然,这是行不通的。 Anyone has any idea?有人有什么想法吗? THX!谢谢!

A more complete version, as suggested by @Austin @Austin 建议的更完整的版本

<!DOCTYPE html>
<html>
<body>
<style type="text/css">

</style>
<p id="test">test</p>
<p id="objectid"></p>

<script>
function test(s){
    document.getElementById("test").innerHTML+=s;
}

function somelistener(obj){
    test(obj.id);
}

function myfunction(obj,parentobj){ 
    var o=document.createElement("div");
    o.innerHTML='<input type="button" onclick="somelistener(' + obj + ')" />';

    o.onclick = function () {
        someListener(obj)
    }
parentobj.appendChild(o.firstChild);
}

myfunction(document.getElementById("objectid"),document.getElementById("test"));

</script>

</body>
</html>

The above example does not work because the output of obj to text is [Object object] , so essentially, you are calling someListener([Object object]) .上面的示例不起作用,因为obj到文本的输出是[Object object] ,所以本质上,您正在调用someListener([Object object])

While you have the instance of the element in o , bind to it's click using javascript:当您在o中有元素的实例时,使用 javascript 绑定到它的单击:

function myfunction(obj,parentobj){ 
    var o=document.createElement("div");
    o.innerHTML='<input type="button" />';

    o.onClick = function () {
        someListener(obj)
    }

    parentobj.appendChild(o.firstChild);
}

I have created a working fiddle for you here: JSFiddle我在这里为您创建了一个工作小提琴: JSFiddle

function myfunction(obj,parentobj){ 
        var o=document.createElement("div");
         o.innerHTML="<input type='button' onclick='somelistener("+JSON.stringify(obj)+")'/>"; 
                                  parentobj.appendChild(o.firstChild);
            } 
    // my similar problem, function a was called in a jsonArray loop in the dataTable initiation
    function a(data, type, obj) {
                         var str = "";
                         str += "<span class='button-group'>";
                         str +="<a onclick='chooseData1("+JSON.stringify(obj)+")'>[选择]</a>";
                         str += "</span>";
                         return str;
                                            }
function chooseData1(data){
                        console.log(data);
                  }

Old question whose answers I didn't quite understand, but the simplest solution is to combine the functions encodeURIComponent and JSON.stringify , that is, you stringify the object and then escape those special characters, and then reverse the process inside the function老问题的答案我不太明白,但最简单的解决方案是结合函数encodeURIComponentJSON.stringify ,即您将对象字符串化,然后转义那些特殊字符,然后在函数内部反转过程

var htmlStr = `<button onclick="myFunction('${encodeURIComponent(JSON.stringify(obj))}')"></button>`

function myFunction(obj) {
  obj = JSON.parse(decodeURIComponent(obj))
  // do something with obj
}

Test here:在这里测试:

 var obj = {a: 'hey there', b: 1} var htmlStr = `<button onclick="myFunctions('${encodeURIComponent(JSON.stringify(obj))}')">Click me</button>` $('#mydiv').append(htmlStr) function myFunctions(obj) { obj = JSON.parse(decodeURIComponent(obj)) console.log(obj.a) console.log(obj.b) }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="mydiv"></div>

Just stringify the object using JSON.strigify(obj) and pass into the onclick function as parameter and it will be parsed directly and received in the function as Object.只需使用 JSON.strigify(obj) 对对象进行字符串化,并将其作为参数传递给 onclick 函数,它将被直接解析并作为对象在函数中接收。

function myfunction(obj,parentobj){ 
   var o=document.createElement("div");
   var stringifiedObj = JSON.stringfy(obj)

   o.innerHTML='<input type="button" onclick=`somelistener(${stringifiedObj})` />';
   parentobj.appendChild(o);
}

function somelistener(obj){
   console.log(typeof obj) //Object
}

像这样通过它:

o.innerHTML='<input type="button" onclick="somelistener(this)" />';

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

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