簡體   English   中英

具有可變內容的jQuery選擇器

[英]jQuery Selectors with Variable Content

我寫了這個小jQuery,基本上可以過濾內容。 當用戶單擊按鈕(在本例中為LI元素)時,特定內容在可見性中“切換”。

$( "li:contains('Blog')" ).click(function() { // If a user clicks the "Blog" button
  $( ".Blog" ).toggle('slow') // Hide/Show all blog entries
});

這很好用,但並非所有條目都將是博客-它是完全動態的。 所以我需要一些類似的東西:

$( "li:contains('XYZ')" ).click(function() { // If a user clicks this button
  $( ".XYZ" ).toggle('slow') // Hide/Show all entries belonging to that button
});

本質上,如果有更好的編寫方式:

$( "li:contains('Blog')" ).click(function() {
  $( ".Blog" ).toggle('slow')
  $(this).toggleClass( "secondary" )
});

$( "li:contains('Twitter')" ).click(function() {
  $( ".Twitter" ).toggle('slow')
  $(this).toggleClass( "secondary" )
});

$( "li:contains('Facebpok')" ).click(function() {
  $( ".Facebook" ).toggle('slow')
  $(this).toggleClass( "secondary" )
});

HTML

<ul class="button-group filter-button-group">
    <li class="button tiny">Blog </li>
    <li class="button tiny">Twitter </li>
    <li class="button tiny">Facebook </li>
</ul>

當前的CodePen: http ://codepen.io/anon/pen/RPZaNN

試試這個例子:

$( "li" ).click(function() {
          var elem=$(this);
          var txt=elem.html();
          $( "."+txt).toggle('slow');
          $(this).toggleClass( "secondary" )
});

由於您的情況,您的li和te類名稱的內容相同

<ul class="button-group filter-button-group myfilter">
    <li class="button tiny">Blog</li>
    <li class="button tiny">Twitter</li>
    <li class="button tiny">Facebook</li>
</ul>

然后有一個處理程序

$(".myfilter li").click(function () {
    $("." + $(this).text().trim()).toggle('slow')
    $(this).toggleClass("secondary")
});

甚至最好使用data- *屬性指定類anme

<ul class="button-group filter-button-group myfilter">
    <li class="button tiny" data-class="Blog">Blog</li>
    <li class="button tiny" data-class="Twitter">Twitter</li>
    <li class="button tiny" data-class="Facebook">Facebook</li>
</ul>

然后

$(".myfilter li").click(function () {
    $("." + $(this).data('class')).toggle('slow')
    $(this).toggleClass("secondary")
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM