我有一个具有用户定义方法的元素。该元素是作为更大对象的一部分创建的,并在加载文档时插入。如果我通过直接从对象中寻址元素来调用该方法,我可以随时调用该方法。
元素是tabs[0].bubbles[0].element
,方法是.expand()
(这个对象中有多个元素,每个元素都有自己的 .expand() 方法)
所以,线
tabs[0].bubbles[0].element.expand();
调用该元素的方法。但是,当发生特定事件时,会调用一个函数,我可以从中选择元素,如下所示:
bubble = $(this).parent(); // the bubble element is the event handlers parent
然而,线条
bubble.expand();
// or
$(bubble).expand();
// or
$(bubble)[0].expand();
不要调用该方法。
线
tabs[0].bubbles[0].element.expand();
确实调用了该方法。但是,我不能使用这一行来调用该方法,因为有许多不同的元素,并且我无法从函数中找到数组元素的索引号。
我认为我可能没有选择正确的元素,但是
($(bubble)[0] === $(tabs[0].bubbles[0].element)[0])
返回 true (显然这只发生在bubble
应该对应的元素时tabs[0].bubbles[0].element
)。
tabs[0].bubbles[0].element
不等于$(bubble)[0]
or $(bubble)[0]
。
如何从使用 JQuery 选择的函数中调用该方法?
编辑
我认为问题在于我如何创建对象。对象的元素字段是在这样的构造方法中创建的。
this.element = $('<div class="bubble ' + this.type + '">\
<div class="bubbleCentre ' + this.state + ' "> \
<img class="bubbleIcon" src="img/dash/' + this.icon + '"> \
<span class="status">' + text + '</span> \
</div> \
</div>');
该.expand()
函数是这样创建的。
this.element.expand = function ()
{
// method
alert('method executing');
}
我可以这样调用方法
tabs[0].bubbles[0].element.expand();
但bubble.get(0).expand();
或bubble.expand();
什么都不做。
但是,如果我这样定义方法:
this.element.get(0).expand = function ()
{
// method
alert('method executing');
}
我现在可以按照您的期望调用该方法
bubble.get(0).expand(); // expands bubble as you would expect
当方法被调用时,这就足够了。似乎应该有一种更直接的方法来做到这一点。除了在事件回调函数中选择气泡外,我不明白为什么需要涉及 jQuery。有什么想法吗?
我尝试在定义时从字符串周围删除 $() (并在定义方法时.element
取出),但是无论我尝试什么方式,我都无法调用该方法。.get(0)
.expand()