javascript:将一个对象作为参数传递给字符串中的onclick函数 [英] javascript: pass an object as the argument to a onclick function inside string

查看:103
本文介绍了javascript:将一个对象作为参数传递给字符串中的onclick函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个对象作为参数传递给字符串中的Onclick函数。如下所示:

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

显然,这不起作用。任何人有任何想法? THX!

Obviously, this doesn't work. Anyone has any idea? THX!

一个更完整的版本,如@Austin建议

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>


推荐答案

上面的例子不起作用,因为输出 obj to text is [Object object] ,所以基本上,你正在调用 someListener([Object object])

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

当你在 o 中有元素的实例时,使用javascript绑定到它的点击:

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

我在这里为你创造了一个工作小提琴: JSFiddle

I have created a working fiddle for you here: JSFiddle

这篇关于javascript:将一个对象作为参数传递给字符串中的onclick函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆