[removed] pass an object as the argument to a onclick function inside string

前端 未结 3 1410
温柔的废话
温柔的废话 2020-12-30 00:15

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=do         


        
相关标签:
3条回答
  • 2020-12-30 00:49

    Just do pass it like this :

    o.innerHTML='<input type="button" onclick="somelistener(this)" />';
    
    0 讨论(0)
  • 2020-12-30 00:59

    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

    0 讨论(0)
  • 2020-12-30 01:02
    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);
                      }
    
    0 讨论(0)
提交回复
热议问题