2 回答
TA貢獻2003條經驗 獲得超2個贊
您檢查復選框是否checked使用is(":checked")這將給出 true 或 false,因此取決于此顯示或隱藏 trs。
演示代碼:
$('#search_field').on('keyup', function() {
var value = $(this).val();
var patt = new RegExp(value, "i");
var checks = $(".checkbox").is(":checked"); //check if checkbox is checked
console.log(checks)
if (value != "") {
$('#myTable tbody').find('tr').each(function() {
var condition = $(this).find('td').text().search(patt) >= 0
//checked
if (checks) {
//show and hide..
condition ? $(this).show() : $(this).hide()
} else {
condition ? $(this).hide() : $(this).show()
}
});
} else {
$('#myTable tbody > tr').show()
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Search..." id="search_field">
<input type="checkbox" class="checkbox" checked>
<table id="myTable" border="1">
<thead>
<tr class="myHead">
<th>XDFFD</th>
<th>DFDDY</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>
TA貢獻1828條經驗 獲得超3個贊
這是一個替代版本,使用一個小的 jQuery 擴展來使:contains()大小寫不敏感:
// jQuery extension from https://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; };
});
$('input').on('input', function() {
$('#myTable tbody tr').each((i,tr)=>$(tr).toggle
( $('td:contains('+$('#search_field').val()+')',tr).length>0 === $(".checkbox").is(":checked") )
)
}).first().focus();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Search..." id="search_field">
<input type="checkbox" class="checkbox" checked>
<table id="myTable" border="1">
<thead>
<tr class="myHead">
<th>XDFFD</th>
<th>DFDDY</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 one</td>
<td>2 two</td>
</tr>
<tr>
<td>3 Three</td>
<td>4 Four</td>
</tr>
<tr>
<td>5 FIVE</td>
<td>6 SIX</td>
</tr>
</tbody>
</table>
兩個布爾值的比較===實際上類似于兩個表達式之間的異或條件。結果將是true如果兩個 或都不存在表達式
$('td:contains('+$('#search_field').val()+')',tr).length>0和
$(".checkbox").is(":checked")是true。并且這將直接在方法中使用來.toggle()顯示或隱藏當前的<tr>.
添加回答
舉報
