内联javascript函数调用-元素列表后缺少]
我有一个密码:内联javascript函数调用-元素列表后缺少],javascript,jquery,syntax-error,inline,Javascript,Jquery,Syntax Error,Inline,我有一个密码: var data = $('<span onclick="someFunction(' + element + ');"><a href="#">Element information</a></span>'); 但当span元素尝试调用该函数时,我得到错误: SyntaxError: missing ] after element list someFunction([object Object]); 当我在Firebug中
var data = $('<span onclick="someFunction(' + element + ');"><a href="#">Element information</a></span>');
但当span元素尝试调用该函数时,我得到错误:
SyntaxError: missing ] after element list
someFunction([object Object]);
当我在Firebug中调试它时,我看到
<span onclick="someFunction([object Object]);">
<a href="#">Element information</a>
</span>
我通常如何使用具体元素作为参数调用该函数?在连接中将元素转换为字符串时,您将无法传递该元素。当对象转换为字符串时,它输出:[object]。这就是您在调试中看到的 我的建议是: 您可以将图元作为数据添加到跨度中,如下所示: $('span).data('element',element) 在某些函数中检索它,如: var元素=$(this.data('element') 另一个选项是绑定到Javascript中初始化元素的位置。像这样
function anotherFunction() {
var element = {};
// Initialize element
...
// I have already got the element initialized, now I can bind the click
$('span').click(function() {
// For your debug and validation
console.log(JSON.stringify(element));
});
}
如果尝试使用jQuery构建一些DOM元素,则应执行以下操作:
// Wrong: $('<span onclick="someFunction(' + element + ');"><a href="#">Element information</a></span>');
// Right: build up the element step by step
var data = $('<span/>')
.append(
// build up the child <a> element here
$('<a href="#"/>')
.text("Element information")
//.attr('href',"#") Don't really need this
)
.click(
// Here is a real inline function
function(){
someFunction(element);
}
);
在您的代码中,您的对象似乎实际上是一个jQuery对象,但它不会有任何区别
因此,用于形成onclick
的结果“code”无效:
[
和]
用于在JavaScript中构造数组,就像[1,2]
是一个包含两个元素的数组一样。但是,[object object]
是无效的JavaScript语法,因此会出现错误
无论如何,这不是用事件构建DOM元素的正确方法,即使使用jQuery也是如此。上面显示了正确的方法。您也可以尝试:
var数据=$('')代码>
职能:
someFunction:function(元素){
控制台日志(元素);
..//一些代码
}
调用时应返回JSON对象。元素是什么类型的对象?
// Wrong: $('<span onclick="someFunction(' + element + ');"><a href="#">Element information</a></span>');
// Right: build up the element step by step
var data = $('<span/>')
.append(
// build up the child <a> element here
$('<a href="#"/>')
.text("Element information")
//.attr('href',"#") Don't really need this
)
.click(
// Here is a real inline function
function(){
someFunction(element);
}
);
console.log((new Object()).toString()); // [object Object]
console.log("blah" + (new Object())); // blah[object Object]
someFunction([object Object]);