gpt4 book ai didi

javascript - 为什么 jQuery 对象的属性初始化为空?

转载 作者:行者123 更新时间:2023-11-27 23:55:26 25 4
gpt4 key购买 nike

'use strict';
var Controller = function Controller() {};

Controller.init = function() {
if (!Controller.PROPERTIE.element || !Controller.PROPERTIE.indicator) {
return 'Expected to find [data-controller] and [data-controller-to]';
}

Controller._start();
};

Controller.PROPERTIE = {
element: $('[data-controller]'),
indicator: $('[data-controller-to]'),
state: false
};

Controller._start = function() {
Controller.PROPERTIE.indicator.bind('click', Controller._toggle);
};

Controller._toggle = function() {
Controller.PROPERTIE.element
.animate({
bottom: (Controller.PROPERTIE.state = !Controller.PROPERTIE.state) ? '-110' : '0'
});
};

显然对象属性中的元素不存在,但它们确实存在!有人可以告诉我我是否不能这样使用 javascript 吗?

也许提升中有一些东西破坏了脚本?

我已经尝试将对象放在 init 之前,结果是相同的。

我知道我可以扩展原型(prototype),但我有理由这样使用。

谢谢。

最佳答案

我可以想到三个可能的原因:

  1. 代码在 DOM 解析之前初始化。
  2. 您的 HTML 实际上并不包含与这些选择器匹配的元素。
  3. 在初始化此代码后,将动态创建所需的元素。

在此声明中:

Controller.PROPERTIE = {
element: $('[data-controller]'),
indicator: $('[data-controller-to]'),
state: false
};

解析此代码时,将立即计算两个 jQuery 表达式。如果这段代码没有放置在正文的最末尾,那么这些元素可能还不存在。

通常的解决方案是不在静态声明中初始化这些元素,而是在页面加载后通过调用函数来初始化它们。

如果你真的想让它们成为全局的,那么你可以这样做:

$(document).ready(function() {
Controller.PROPERTIE = {
element: $('[data-controller]'),
indicator: $('[data-controller-to]'),
state: false
};
});

但是,您还必须确保在此代码运行之前不要尝试使用它们。

<小时/>

我能想到的唯一可能的原因是您的 DOM 不包含与您的两个选择器匹配的元素。看起来这很可能是这两个问题之一。由于您没有向我们展示您想要匹配的 HTML 的整体页面结构,因此我们只能告诉您可能的原因。

关于javascript - 为什么 jQuery 对象的属性初始化为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32302935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com