2016-12-26 74 views
0

剃刀/ HTML(很多這樣的):jQuery的每個onclick事件裏面

<div class="directory-item" id="@item_id" name="@item_name" style="padding-left: @(indent_level)px; display: @(display)"> 
    <i class="fa @icon_type"></i> 
    @item.ItemName (id: @item_id, name: @item_name, level: @item.Level) 
    <i class="fa fa-angle-right float-right"></i> 
</div> 

的Javascript:

$(".directory-item").click(function() { 
    $('div[name*=' + this.id + ']').each(function() { 
     if (this.attr('display') == "none") { 
      this.show(); 
     } else { 
      this.hide(); 
     } 
    }); 
}); 

基本問題:你怎麼把一個 「每個」 內部的 「click」 事件並用「this」引用「each」項(每次訪問一個元素)?也許我不應該使用每一個陳述,而是其他的東西?

+0

yes.you應該使用'this'或者甚至包含'$(this)'的jQuery包裝項目來訪問被單擊的項目。然後你可以使用'最近()','find'等方法訪問相關的項目。 – Shyju

+0

你會如何使用find重寫上述內容?基本上,我試圖採用被點擊的div的id,並找到所有包含該id的名稱的div,然後顯示/隱藏切換它們。 – gunslingor

+0

您不應該有多個具有相同Id值的項目!這是無效的HTML。你想達到什麼目的? – Shyju

回答

0

在每個方法的回調中,您可以有2個參數,一個用於索引,第二個用於循環當前迭代的項目。

$(function() { 

    $(".directory-item").click(function() { 

     $('div[name*=' + this.id + ']').each(function (a,b) { 
      if ($(b).attr('display') == "none") { 
       $(b).show(); 
      } else { 
       $(b).hide(); 
      } 
     }); 
    }); 
}); 

如果簡單地更新知名度,你可以使用toggle以及

$('div[name*=' + this.id + ']').each(function (a,b) { 
    $(b).toggle(); 
}); 
+0

attr('display')'???更可能是一個樣式屬性 – charlietfl

0

假設有與做匹配元素的ID單擊了,你應該能夠簡化這名元素:

$(".directory-item").click(function() { 
     $('div[name*=' + this.id + ']').toggle() 
}); 

使用toggle()會顯示這樣的元素,如果它是隱藏的,隱藏它,如果它不是,也沒有必要each,因爲它會循環遍歷所有匹配的元素