【发布时间】:2018-06-23 15:33:29
【问题描述】:
我正在使用 jQuery 选择器来选择具有特定类的所有元素。然后我继续为每个选定的元素创建一个 JavaScript 类的新实例。
在后面的代码中,我选择了 jQuery 元素并且需要访问类 JavaScript 类实例。如何将类的实例分配给 jQuery 选定元素?
这是我想要实现但不起作用的代码示例。不确定执行此操作的正确方法:
let sampleElement = $('#sample-element');
// I want to assign the class instance to the element
sampleElement.sampleClass = new SampleClass(sampleElement);
// I want to call a function inside the class later
sampleElement.sampleClass.alertElementText();
下面是我想要实现的更广泛的代码示例:
HTML
<div id="sample-element-1" class="sample-element">
This is some text!
</div>
<div id="sample-element-2" class="sample-element">
This is some more text!
</div>
jQuery
(function ($) {
class SampleClass {
constructor(element) {
this.element = this;
}
alertElementText() {
alert(this.element.text());
}
}
jQuery(document).ready(function () {
let elements = $('.sample-element');
elements.each(function() {
new SampleClass($(this));
// I need a way to assign the instance of the class
// to the element so I can access it later
// Just unsure of the syntax
});
// Here I want to access the class and call the alert function
// The below lines won't work but it gives an indication of what I want to achieve
$('#sample-element-1').alertElementText();
$('#sample-element-2').alertElementText();
});
}(jQuery));
【问题讨论】:
-
如果你想使用
$('#sample-element-1').alertElementText();,那么你应该分配通常的$.fn.alertElementText = function(){ alert(this.text()); };。不创建 ES6 类。
标签: javascript jquery html class ecmascript-6