javascript - 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 的主要区别是什么吗?
解决方案
这是因为您使用 JQuery 链接方法(加入它们),因此,您只返回一件事。
使用 Vanilla JavaScript,您没有链接方法(并且您不能将 JQuery 方法与纯 JavaScript 方法链接。因此,您modal.body_el()
在调用 querySelector 之后返回 and,但您不能调用 querySelector,因为您已经返回了一些东西。
解决方案:
返回时仅使用 JQuery 方法或仅使用纯 JavaScript 方法。
推荐阅读
- javascript - 如何使用 javascript 从浏览器启动命令提示符?
- flutter - Flutter 调用 StatefulWidget 的构造函数导致无法计算表达式
- css - 子进程继承的事件目标不会影响父 React
- python - 添加后程序在文件中找不到新对象
- php - 联系表格 7 提交后更改用户角色
- c# - 使用个人用户帐户将 IdentityServer 添加到 Razor 应用程序 - 发现多个 DbContext
- reactjs - Material UI - 带有 2 个变量的自动完成表单标签
- r - Hugo Theme Academic:在 about 部分重命名“interests”
- excel - 努力寻找公式来确定某个单词是否出现在同一个帐户中
- time-complexity - 平均案例分析与摊销分析