2017-06-22 45 views
1

完全可以將一些JQuery轉換爲PolymerJS嗎?將jQuery代碼轉換爲Polymer?

問題:希望某個CSS類僅適用於被單擊的元素。

我曾在JQuery中工作,但想知道它是否可以在Polymer中完成? 我知道如何添加和刪除活動元素的CSS,而不是如何從除活動元素之外的所有元素中刪除。

組件被施加到

<iron-ajax id="userGet" handle-as="json" method="GET" on-response="setUser"></iron-ajax> 
    <div class="iron-list-container"> 
     <iron-list id="list" items="setUser" as="user" > 
      <div class="item" id="item"> 
       <!-- USER INFO STUFF GOES HERE --> 
      </div> 
     </iron-list> 
    </div> 

GIF of functionality I have with the JQuery

JQuery的

toggleLeftBorder: function() { 
    $(".item").click(function() { 
     $('.item').removeClass('addBorderLeft'); 
     $(this).addClass('addBorderLeft'); 
    }) 
}, 

PolymerJS到目前爲止

toggleLeftBorder : function() { 
    /* this line will add the necessary css class to selected elements */ 
    this.$.item.classList.add('addBorderLeft'); 
}, 
+0

您是否需要支持選擇多個項目?它看起來像從jQuery片段,這是不可能的,但只是想確保我明白。 – zacharytamas

+0

你在找什麼基本上是一個關於如何編寫聚合物代碼的教程..因爲如何將jQuery代碼轉換爲香草是非常明顯的,所以你要求我們教你如何編寫一個簡單的聚合物代碼?是不是已經有在線教程? – vsync

+0

@zacharytamas:我添加了一個GIF,使用了我想要重現的JQuery的當前功能。 – physicsboy

回答

1

像jQuery提供的那樣,在Polymer中沒有這樣做。聚合物儘可能減輕重量,並且不添加很多DOM操作工具。

香草JS的等效線可能是:

this.shadowRoot.querySelectorAll('.addBorderLeft') 
    .forEach(item => item.classList.remove('addBorderLeft'); 

既然你只希望一次選擇一個項目,你可以只跟蹤先前選擇的項目,並從中取出類,你設置的前新選一個:

toggleLeftBorder : function() { 
    if (this.selectedUserElement) { 
    this.selectedUserElement.classList.remove('addBorderLeft'); 
    } 

    this.selectedUserElement = this.$.item; 
    this.selectedUserElement.classList.add('addBorderLeft'); 
}, 

然而,由於您使用的iron-list它帶有選擇在烤,所以你應該能夠做到這一點聲明是這樣的:

<iron-ajax id="userGet" handle-as="json" method="GET" on-response="setUser"></iron-ajax> 

<div class="iron-list-container"> 
    <iron-list id="list" items="[[setUser]]" as="user" 
    selection-enabled selected-item="{{selectedUser}}"> 
    <div class="item"> 
     <!-- USER INFO STUFF GOES HERE --> 
    </div> 
    </iron-list> 
</div> 

這將做到以下幾點:

  • 創建一個名爲selectedUser你的元素屬性這始終是當前選定的用戶。無論如何,我懷疑你在元素/應用程序的其他地方需要這個。
  • selected類添加到所選iron-list項目。請注意,這與addBorderLeft類不同,因此您需要將樣式放在.selected上。