如何在javascript函数中传递JSON对象作为函数参数? [英] How to pass a JSON object in javascript function as a function parameter?
问题描述
在我的js函数中,我创建一个div和一个链接
,当点击链接时,我会传递一个参数另一个js函数?我的代码出了什么问题?
In my js function,I create a div and a link
,when click the link,I will pass a parameter the another js funcion?What's wrong with my code?
js function1
//pass a json:the browser show wrong:SyntaxError: missing ] after element list
//passJson([object Object])
var dataItem=getDataItem();//a json object which has title and name property
var divStr="<div><a style='cursor: pointer' onclick='passJson(" + dataItem +")'><span title='spantitle'><i class='icon-mouse'></i></span></a>;</div>";
所以我尝试将[]添加到函数中,但它仍然显示错误。
So I try to add the "[]" to the function,but it still show wrong.
js function2
//pass a json:the browser show wrong:SyntaxError: missing ] after element list
//passJson([object Object])
var dataItem=getDataItem();// a json object which has title and name property
var divStr="<div><a style='cursor: pointer' onclick='passJson([" + dataItem +"])'><span title='spantitle' ><i class='icon-mouse'></i></span></a>;</div>";
推荐答案
通常,您不会将其称为JSON对象。您只需将其称为JavaScript对象。
Typically, you don't call it a JSON object. You just call it a JavaScript object.
您的代码的方式,您不需要进行字符串连接。您可以执行 onclick ='passJson(dataItem)'
,如
The way your code is, you don't need to do string concatenation. You can just do onclick='passJson(dataItem)'
as in
function passJson(obj) {
console.log(obj);
}
var dataItem={ title: "hello", name: "snoopy" }; //a json object which has title and name property
var divStr="<div id='foo'><a style='cursor: pointer' onclick='passJson(dataItem)'><span title='spantitle'><i class='icon-mouse'></i>hmmm</span></a>;</div>";
$("body").append(divStr);
当你点击链接hmmm时它会起作用。
and it will work when you click on the link "hmmm".
您可能希望单独添加标记,然后将单击处理程序绑定到链接,因为通常情况下,我们希望采用不引人注目的JavaScript 。
You probably want to add the markup separately, and then bind a click handler to the link, because typically, we would like to go with the approach of unobtrusive JavaScript.
这篇关于如何在javascript函数中传递JSON对象作为函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!