2017-03-09 83 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>