簡體   English   中英

jQuery。 找到所有 <tr> 包含所選文字 <option>

[英]Jquery. Find all <tr> containing text from selected <option>

單擊按鈕后,我嘗試顯示所有包含選項中所選文本的行,這是我的代碼:

<select>
 <option>text1</option>
 <option>text2</option>
 <option>text3</option>
 <option>text4</option>
</select>
<button class="show"></button>
<button class="hide"></button>
<table>
 <tr>
  <td>text1</td><td>....</td>
 </tr>
 <tr>
  <td>text2</td><td>....</td>
 </tr>
 <tr>
  <td>text3</td><td>....</td>
 </tr>
 <tr>
  <td>text1</td><td>....</td>
 </tr>
</table>

我試圖做這樣的事情,但它不起作用:

$(function(){
  b = $("tr");
  $(".show").on("click", function(){
   var a = $("select option:selected").text();
   $(b).hide();
   if ($("tr:contains('"+a+"')").length) 
    $(this).closest(tr).show();
 });

 $(".hide").on("click", function(){
  $(b).show();              
 });    
});

有人可以幫我嗎,:)

您需要這樣的東西。 不要污染全局空間並使用適當的選擇器。 並且無需再次包裝jQuery對象。

$(function() {
    var b = $("table");
    $(".show").on("click", function() {
        var a = $("select option:selected").text();
        b.find("tr").hide().end().find("td:contains('" + a + "')").parent().show();
    });
    $(".hide").on("click", function() {
        b.find("tr").show();
    });
});

試試看:您可以使用each來檢查每個tr的選定選項文本並使其可見。 $(this)本身是TR無需使用closest('tr')

$(function(){
  b = $("tr");
  $(".show").on("click", function(){
   var a = $("select option:selected").text();
   b.hide();
   //if ($("tr:contains('"+a+"')").length) 
   // $(this).closest(tr).show();
   b.each(function(){
     if($(this).text().indexOf(a)!=-1)
     {
       $(this).show();
     }
  });
 });

 $(".hide").on("click", function(){
  b.show();              
 });    
});

您不能使用contains原因匹配任何簡單包含測試的元素(選擇所有包含指定文本的元素)。 但是您可以使用each td並用相同的文本匹配任何td並顯示parent( tr ),例如:

 b = $("tr"); $(".show").on("click", function() { var a = $("select option:selected").text(); $(b).hide(); $("td").each(function() { if ($(this).text() == a) { $(this).parents("tr").show(); } }); }); $(".hide").on("click", function() { $(b).show(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option>text1</option> <option>text2</option> <option>text3</option> <option>text4</option> </select> <button class="show">show</button> <button class="hide">hide</button> <table> <tr> <td>text1</td> <td>....</td> </tr> <tr> <td>text2</td> <td>....</td> </tr> <tr> <td>text3</td> <td>....</td> </tr> <tr> <td>text1</td> <td>....</td> </tr> </table> 

讓您的按鈕直接在此處運行功能。

function show() {
   var needle = $("select option:selected").text();
   $('#myTable td').each(function() {
        if ($(this).text() === needle) $(this).show();
   });
}
function hide() {
   var needle = $("select option:selected").text();
   $('#myTable td').each(function() {
        if ($(this).text() === needle) $(this).hide();
   });
}

看看這個(jsFiddle)

暫無
暫無

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

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