首页 > 解决方案 > 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 的主要区别是什么吗?

标签: javascriptjquery

解决方案


这是因为您使用 JQuery 链接方法(加入它们),因此,您只返回一件事。

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

解决方案:

返回时仅使用 JQuery 方法或仅使用纯 JavaScript 方法。


推荐阅读