Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
127
rated 0 times [  128] [ 1]  / answers: 1 / hits: 59060  / 10 Years ago, sun, april 13, 2014, 12:00:00

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

More From » jquery

 Answers
19

Typically, you don't call it a JSON object. You just call it a JavaScript object.



The way your code is, you don't need to do string concatenation. You can just do onclick='passJson(dataItem)' as in



http://jsfiddle.net/6LzCA/5/



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


and it will work when you click on the link hmmm.



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.


[#71486] Thursday, April 10, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jericho

Total Points: 204
Total Questions: 98
Total Answers: 108

Location: Thailand
Member since Thu, Apr 22, 2021
3 Years ago
;