-1

考虑以下情况:
我有一个 jQuery 对象,$wrapper = $(this);. 这发生在 init 调用中,如下所示$('#unique-wrapper-id').initWrapper()'。正如您已经可以想象的那样initWrapper(),它是jQuery.fn.

现在,仍然在initWrapper()通话中,我添加了一个函数来$wrapper喜欢这个

$wrapper.getValue = function() { /* typical wrapper function */}

然后,在一个回调中,该回调在我调用的包装器中单击一个元素时执行$wrapper.trigger('change')。在另一端,我收听常规的 jQuery 更改事件,这就是它不再起作用的地方。

$('#unique-wrapper-id').change(function() {
    var $wrapper = $(this);
    $wrapper.getValue(); // $wrapper.getValue() is not a function
});

好的,所以 jQuery 更改事件过程中的某个地方getValue()会丢失。没问题,我只需在 init 调用中将它附加到 DOMElement 本身

$wrapper[0].getValue = function { /* typical wrapper function */ }

这按预期工作,我可以getValue()在侦听端的 jQuery 对象后面的 DOMElement 上执行该方法。

但是,有两件事让我感到困扰:

  • 为什么getValue()jQuery 对象在更改事件过程中会丢失?
  • 为什么 jQuery 构造函数 ( ) 不将 DOMElementvar $wrapper = $(this);的函数复制到 jQuery 对象中?getValue()
4

1 回答 1

1

如果$wrapper是相同的元素,您应该能够在其中getValue存储.data()

var getValue = function() { /* typical wrapper function */};
$wrapper.data("getValue", getValue);

$("#unique-wrapper-id").change(function() {
    var $wrapper = $(this);
    $wrapper.data().getValue();
});
于 2016-03-22T20:43:02.273 回答