【问题标题】:Javascript: run object method on DOM object selected through other propertyJavascript:在通过其他属性选择的 DOM 对象上运行对象方法
【发布时间】:2017-07-30 15:22:25
【问题描述】:

我对 javascript 很陌生。

在这里,我无法在通过同一对象的另一个属性选择的 DOM 元素上运行对象方法。我怀疑我的想法有问题!

提前感谢您的任何帮助。

var Arrow = function() {
    this.current = $('.arrow');
    this.previous = null;
    this.bend = function() {
        // do bend
    };
};

var arrow = new Arrow();

arrow.current.bend();

【问题讨论】:

  • $('.arrow'); 可能选择多个元素(所有元素都属于arrow 类)。您将函数bend 添加到Arrow,但尝试在arrow.current 中调用它。
  • arrow.bend();

标签: javascript jquery methods properties prototype


【解决方案1】:

bend() 是 Arrow 的一个方法,不是当前的。使用 arrow.bend(),它也可以使用 this.current 访问电流。

【讨论】:

    【解决方案2】:

    arrow.current.bend 未定义。

    你已经定义了:

    • this.current 作为 DOM 元素数组。
    • this.bend 作为带有函数的方法。

    因此,您可以调用:

    • arrow.current >> 返回 DOM 数组
    • arrow.bend() >> 执行函数bend。
    • arrow.current.bend() 不存在。

    另外,请注意 arrow.current 是一个数组。您首先需要获取每个元素:

    for (element of arrow.current) { element.bend(); }
    

    但是,如前所述,默认情况下元素没有弯曲元素,并且您在任何时候都没有附加。只有箭头具有弯曲属性。

    我希望这可以指导您了解为什么这不起作用。 但是,如果您想就您想要实现的目标提出问题,也许我们可以帮助解决它。

    【讨论】:

      【解决方案3】:

      您需要在 arrow 对象上调用 bend()。在bend()函数中,你做你需要做的。

      var Arrow = function() {
          this.current = $('.arrow');
          this.previous = null;
          this.bend = function() {
              // do bend
              current.style = 'bent';
          };
      };
      
      var arrow = new Arrow();
      arrow.bend();
      

      【讨论】:

        【解决方案4】:

        所以两件事。

        你在错误的对象上调用了正确的方法

        arrow.bend(); // not arrow.current.bend()
        

        第二个可能的问题是this.current = $('.arrow');。要从DOM 获取元素,您应该确保它已完全加载。我建议以下

            var Arrow = function($arrow) {
                this.current = $arrow;
                this.previous = null;
            };
        
            // To avoid creating the `bend` in every instance of Arrow
            Arrow.prototype.bend = function() {
                    console.log(this.current.attr('id'));
                };
            
            $(function () {
                // Now it's certain that the DOM is completely loaded
                var arrow = new Arrow($('.arrow').first());
            
                arrow.bend();
            });
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <div class="arrow" id="toto">arrow<div>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-23
          • 1970-01-01
          • 1970-01-01
          • 2016-05-29
          • 1970-01-01
          相关资源
          最近更新 更多