提问者:小点点

在对象内部无法访问querySelector


因此,我正在构建一种基于对象的模型方法,并试图将所有现有的jQuery转换为纯JavaScript调用,但我遇到了一些问题。

所以我有一个基本的基础:

// Initialize modal
let modal = {

// Define an element for namespacing / This will be class based.
    el: null,

    settings: {

        // Define the title
        title: null,

        // If it has a cogwheel or not
        cogwheel: false,

        // Cogwheel trigger
        cogwheel_trigger: '',

    },

    /**************************************************************************/

    header_el: function() {
        // Break down into title/cogwheel?
        // The close button was removed in top right corner
    },

    body_el: function() {
        // Will it be a container?
        // Will there be levels/columns?
    },

    footer_el: function() {
        // What buttons will be included?
        // Do we data target the Save/Close separately?
        // What buttons should we provide?
    },

    /**************************************************************************/

    // Find the modal parent/child.
    findAncestor: function() {
        // Empty
    },

    // Show the modal
    show_modal: function() {
        // Empty
    },

    // Close the modal
    close_modal: function() {
        // Empty
    },

    /**************************************************************************/
    // Controls: Things the user can interact with.

    cogwheel_ctrl: function() {
        // Empty
    },

    add_icon_ctrl: function() {
        // Empty
    },

    remove_icon_ctrl: function() {
        // Empty
    },

    add_button_ctrl: function() {
        return modal
            .body_el()
            document.querySelector('[data-ctrl="add-button"]');
    },

    save_button_ctrl: function() {
        return modal
            .footer_el()
            .find('[data-ctrl="save-button"');
    },

    close_button_ctrl: function() {
        return modal
            .footer_el()
            .find('[data-ctrl="close-button"');
    },
}

由于某些原因,当使用jQuery.find()调用时,它都运行得很好,但是当使用Document.QuerySelector调用JS替代项时,我会得到一个unreachable code错误,如下所示:

谁能给我解释一下.find()调用和传统JS的主要区别是什么?


共1个答案

匿名用户

这是因为在JQuery中,您要链接方法(join它们),因此,您只返回一个东西。

使用常规JavaScript,您没有链接方法(也不能用纯JavaScript方法链接JQuery方法)。因此,您返回modal.body_el()并在调用querySelector之后,但您不能调用querySelector,因为您已经返回了一些东西。

解决方案:

返回时要么只使用JQuery方法,要么只使用纯JavaScript方法。