Jquery.查找所有<tr>包含来自所选<选项>

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

本文关键字:gt lt 选项 tr 查找 Jquery 包含      更新时间:2023-09-26

我试图在点击按钮后显示所有包含选项中所选文本的行,这是我的代码:

<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是否有选定的选项文本,并使其可见。不需要使用closest('tr'),因为$(this)本身就是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与相同的文本进行匹配,并显示父级(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)。