Javascript:通过其他属性选择的DOM对象上运行对象方法

时间:2017-03-09 15:07:32

标签: javascript jquery methods properties prototype

我对javascript很新。

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

提前感谢任何帮助。

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

var arrow = new Arrow();

arrow.current.bend();

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

未定义arrow.current.bend。

您已定义:

  • this.current作为DOM元素的数组。
  • this.bend as function with a function。

因此,您可以致电:

  • arrow.current>>返回DOM数组
  • arrow.bend()>>执行功能弯曲。
  • arrow.current.bend()不存在。

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

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

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

我希望这可以指导你为什么这不起作用。 但是,如果你想打开一个关于你想要达到的目标的问题,也许我们可以帮助你修复它。

答案 2 :(得分:1)

您需要在bend()对象上调用arrow。在bend()函数中,您可以执行您需要执行的操作。

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

var arrow = new Arrow();
arrow.bend();

答案 3 :(得分:1)

所以有两件事。

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

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>