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

北城以北 提交于 2019-12-18 12:15:28

问题


I would like to pass an object as parameter to an Onclick function inside a string. 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

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

回答1:


The above example does not work because the output of obj to text is [Object object], so essentially, you are calling someListener([Object object]).

While you have the instance of the element in o, bind to it's click using 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




回答2:


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



回答3:


Just do pass it like this :

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


来源:https://stackoverflow.com/questions/12109811/javascript-pass-an-object-as-the-argument-to-a-onclick-function-inside-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!