我正在使用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));
使用 jQuery 数据创建了一个解决方案。感谢@jaromanda X为我指明了正确的方向。
解决方案代码:
let sampleElement = $('#sample-element');
// Here we assign the class instance to a unique key 'sampleClass'
sampleElement.data('sampleClass', new SampleClass(sampleElement));
// Here the class instance can be accessed and the function called
sampleElement.data('sampleClass').alertElementText();
带有解决方案的扩展代码:
(function ($) {
class SampleClass {
constructor(element) {
this.element = this;
}
alertElementText() {
alert(this.element.text());
}
}
jQuery(document).ready(function () {
let elements = $('.sample-element');
elements.each(function() {
// Here we assign the class instance to a unique key 'sampleClass'
$(this).data('sampleClass', new SampleClass($(this)));
});
// Now we can access the class instance when using other selectors
$('#sample-element-1').data('sampleClass').alertElementText();
$('#sample-element-2').data('sampleClass').alertElementText();
});
}(jQuery));