[英]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();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.