2017-03-09 87 views
1

我对JavaScript很陌生。Javascript:通过其他属性选择DOM对象的运行对象方法

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

在此先感谢您的帮助。

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

var arrow = new Arrow(); 

arrow.current.bend(); 
+0

'$( '箭头');'可能选择多个元素(所有带班'arrow')。将函数'bend'添加到'Arrow',但尝试在'arrow.current'中调用它。 – Arg0n

+0

'arrow.bend();' – dfsq

回答

3

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

1

arrow.current.bend未定义。

您已经定义:

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

因此,您可以拨打:

  • arrow.current >>海外省
  • arrow.bend的返回Array()>>执行功能的弯曲。
  • arrow.current.bend()不存在。

此外,请注意arrow.current是一个数组。你首先需要得到各要素:

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

然而,正如前面所说的,元素没有默认情况下,弯曲元素,你有没有在任何时候追加。只有箭头具有弯曲属性。

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

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(); 
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>

相关问题