将JavaScript类(ES6)分配给jQuery selected元素

时间:2018-01-15 00:35:26

标签: javascript jquery html class ecmascript-6

我正在使用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));

1 个答案:

答案 0 :(得分:0)

使用jQuery data创建解决方案。感谢@jaromanda X指出我正确的方向。

解决方案代码:

static

带解决方案的扩展代码:

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();