开发者

"Expected ]" error while passing an object as parameter to js function

I am trying to pass an object as parameter to the javascript function as:

    .html('<span class="link" oncli开发者_开发技巧ck="javascript:ShowEventDetails(' + event + ',' 
    + event.Id + ',' + event.Name + ',' + view + ')">' + event.title 
+ '</span>')

In the above js, the event and view are objects from the jquery calendar Full Calendar, which i am passing to call a js function.

It throws an error, Expected ']'. What may be problem or how to pass an object as above?

It shows "javascript:ShowEditEventDetails([object Object],1,'Name',[object Object])" while looking in firebug.


You can't pass an object in that way, because when you concatenate the HTML string of your span element, all the operands of the + operator are converted toString, including the event object, that's why you get "[object Object]":

'' + {} == "[object Object]"; // an empty object

I would recommend you to bind the click event programmatically:

// ...
var $span = $('<span class="link">' + event.title + '</span>');
$span.click(function () {
  ShowEventDetails(event, event.Id, event.Name, view);
});

$('#otherElement').append($span);
// ...


That's because ShowEventDetails isn't being passed event, it's being passed String(event), which is [object Object], which yields a syntax error. Assuming event and view are global variables, use this instead:

.html('<span class="link" onclick="javascript:ShowEventDetails(event,' 
      + event.Id + ',' + event.Name + ',view)">' + event.title 
      + '</span>')

You shouldn't be using .html for such a thing though. This solution is better and doesn't require global variables:

.addClass("link")
.click(function () {
  ShowEventDetails(event, event.Id, event.Name, view)
})
.text(event.title);


What's Going Wrong

event and view are both objects. When you concatenate an object to a string (as you're doing with '...ShowEventDetails(' + event + ','...), JavaScript casts the object to a string, resulting in the nearly useless [object Object] text you see in FireBug. When the JavaScript interpreter later tries to parse [object Object] as code, it blows up because it is invalid syntax.

How to Fix It

The easiest thing to do is set your event handler programmatically:

var mySpan = $('<span class="link" />');
mySpan.text(event.title);
mySpan.click(function (ev) {
  ShowEventDetails(event, event.Id, event.Name, view);
});

parentElement.append(mySpan);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜