如何在javascript字符串中附加对象作为参数的函数?

时间:2016-04-13 18:53:42

标签: javascript

<script>
  //some code here
  var content = '<div onclick="populatedata(\'' + obj.Records[t] + '\')" >';

  function populatedata(obj) {
    console.log(typeof obj);
  }
</script>

现在上面代码的输出是字符串,但是我想要函数populatedata中的对象内容。

3 个答案:

答案 0 :(得分:1)

As @nnnnnn建议我在功能中传递了记录索引,并在populatedata收到了它。

<script>
  //some code here
  var content = "<div onclick="populatedata("+t+")>";

  function populatedata(index) {
    console.log(obj.Records[index]); //this is just for illustration
    //further processing here
}
</script>

答案 1 :(得分:0)

你没有澄清obj.Records[t]是什么类型,但我想这是一个对象。所以你有问题,因为与String连接的结果总是一个新字符串,toString()应用于非字符串类型(在你的情况下为obj.Records[t])。

您需要手动对对象进行字符串化,以便自己控制字符串演示:

var content = '<div onclick="populatedata(' + JSON.stringify(obj.Records[t]) + ')">';

然后这种连接的结果就像(如果obj.Records[t] = {name: 123}):

<div onclick="populatedata({"name":123})">

允许populatedata调用适当的参数。

答案 2 :(得分:0)

如果您希望能够进一步处理populatedata的参数,您首先需要对其进行字符串化,然后将您的函数更改为将typeof记录到只是对象。

var content = "<div onclick='populatedata(" + JSON.stringify(obj.Records[t]) + ")'>test</div>";
function populatedata(obj) {
  // do things with obj here
  console.log(obj);
}

但是,正如Oriol在对您的问题的评论中提到的那样,您可能不希望采用这种方法。最好是:

  • 通过dom API管理处理程序
  • 以编程方式传递数据对象,而不是将它们嵌入到dom