对象没有方法’apply’
我正在动态创建一些DOM元素,比如
var anchorElement = jQuery('',{text:property.text}); var liElement = jQuery('',{"class":"navlink_"+i,id:"navlink_"+i}); anchorElement.on('click',property.fnctn); liElement.append(anchorElement); parentID.append(liElement);
其中property
是JSON对象。 property.text
是我想要放入锚元素的文本。 (工作良好)
我想将click事件处理程序附加到该锚元素。 需要绑定到该元素的函数在JSON中指定,我们可以像访问它一样访问它
property.fnctn
以下行应将事件处理程序绑定到anchor元素。
anchorElement.on('click',property.fnctn);
这不起作用,所以我尝试将其转换为字符串,
anchorElement.on('click',property.fnctn.toString());
没有成功……
当我单击此链接时,错误将记录在控制台中
该对象没有方法’apply’。 是什么原因…???
我可以通过轻微的工作来完成它
anchorElement.attr('onclick',property.fnctn+"()");
上面的语句有效,但我想知道为什么.on()
API不起作用。
谢谢:)AÐitya。
更新 :
你说过property.actfn
是一个字符串, "paySomeoneClick"
。 最好不要将字符串用于事件处理程序,而是使用函数 。 如果您希望调用字符串中定义的函数paySomeoneClick
,并且该函数是全局函数,则可以执行以下操作:
anchorElement.on('click',function(event) { return window[property.fnctn](event); });
这是有效的,因为全局函数是全局对象的属性,可以通过浏览器上的window
获得,也可以使用下面描述的括号表示法。
如果函数在您引用的对象上,则:
anchorElement.on('click',function(event) { return theObject[property.fnctn](event); });
这是有效的,因为在JavaScript中,您可以通过两种方式访问对象的属性:带有文字属性名称的虚线表示法( foo.bar
访问foo
上的bar
foo.bar
)和带有字符串属性名称的括号表示法( foo["bar"]
) 。 它们是等价的,当然除了括号内的表示法,字符串可以是表达式的结果,包括来自属性值,如property.fnctn
。
但我会建议退一步并重构一下,这样你就不会在字符串中传递函数名。 有时这是正确的答案,但根据我的经验,并非经常。 🙂
原始答案 :
(这假设property.fnctn
是一个函数,而不是一个字符串。但可能对某人有用……)
代码
anchorElement.on('click',property.fnctn);
将函数附加到事件,但在调用函数期间, this
将引用DOM元素, 而不是 property
对象。
要解决这个问题,请使用jQuery的$.proxy
:
anchorElement.on('click',$.proxy(property.fnctn, property));
…或ES5的Function#bind
#bind:
anchorElement.on('click',property.fnctn.bind(property));
…或关闭:
anchorElement.on('click',function(event) { return property.fnctn(event); });
更多阅读(在我的博客上):
- 神话方法
- 你必须记住
this
- 关闭并不复杂