gpt4 book ai didi

jquery - 无法在 JQuery 对象上调用扩展方法

转载 作者:行者123 更新时间:2023-12-01 03:02:51 24 4
gpt4 key购买 nike

我有类似以下内容的 HTML:

<div id="quoteContainer">
<div class="quote prototype"></div>
<div class="quote live q0"></div>
<div class="quote live q1"></div>
<div class="quote live q2"></div>
<div class="quote live q3"></div>
...
</div>

其中每个事件 div 都是原型(prototype) div 的副本。这是制作副本的代码:

quote = $(".quote.prototype").clone().show()
.removeClass("prototype").addClass("live")
.addClass(foo)
.appendTo("#quoteContainer");

$.extend(quote, QuoteCalculator);
quote.setQuoteClass(foo);

Foo 是一个由“q”和引号数量组合而成的变量。 QuoteCalculator 类有几个我想调用的方法,包括(例如)shout()。以下是 QuoteCalculator 的一部分:

var QuoteCalculator = {
...

shout: function() {
console.log("hello from calculator");
},

...
};

在程序的另一点,我想调用shout方法。这是我的代码:

$(".quote.live").each(function() {
this.shout();
});

这是 Firebug 所说的:this.shout 不是一个函数[中断此错误] this.shout();

编辑:这是奇怪的部分:调用 quote.setQuoteClass(foo) 不会生成错误。相反,它工作得很好。

为什么会出现这个问题,是什么原因造成的,如何解决?

最佳答案

您的扩展:

$.extend(quote, QuoteCalculator);

正在扩展 jQuery 函数的实例。它没有扩展 jQuery 原型(prototype),以便对先前集合中的元素(quote)进行任何新查询也能获取这些方法。

$(".quote.live")

^^ 这是一个新查询,会产生一个新的 jQuery 实例,该实例未连接到您扩展的 quote 中存储的实例。

您需要查看plugin authoring以及如何扩展 jQuery“类”(jQuery 函数的原型(prototype)),以便工厂返回的所有 jQuery 实例都具有您想要的方法。

关于jquery - 无法在 JQuery 对象上调用扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6781314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com