根据表格单元格的内容隐藏表格行 [英] Hide table row based on content of table cell

查看:28
本文介绍了根据表格单元格的内容隐藏表格行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一些 jQuery 来显示一些表格行并根据每行中第一个表格单元格的内容隐藏其他表格.

I want to make some jQuery that shows some table rows and hides others based on the content of the first table cell in each row.

当我单击一个列表项时,我希望 jQuery 检查该项的第一个字母是否与我的标记中任何表格单元格中的第一个字母匹配,如果是,则应显示父表格行并隐藏其他行.

When I click a list item I want jQuery to check if the first letter of the item matches the first letter in any table cell in my markup, if so the parent table row should be shown and other rows should be hidden.

这是我的标记:

<ul>
<li>A</li>
<li>B</li>
<li>G</li>
</ul>

<table>

<tr>
<td>Alpha1</td>
<td>Some content</td>
</tr>

<tr>
<td>Alpha2</td>
<td>Some content</td>
</tr>

<tr>
<td>Alpha3</td>
<td>Some content</td>
</tr>

<tr>
<td>Beta1</td>
<td>Some content</td>
</tr>
<tr>
<td>Beta2</td>
<td>Some content</td>
</tr>
<tr>
<td>Beta3</td>
<td>Some content</td>
</tr>


<tr>
<td>Gamma1</td>
<td>Some content</td>
</tr>

<tr>
<td>Gamma2</td>
<td>Some content</td>
</tr>

<tr>
<td>Gamma3</td>
<td>Some content</td>
</tr>
</table>

因此,如果我按A",浏览器中将呈现以下内容:

So if I press "A" this is what is rendered in the browser:

<ul>
<li>A</li>
<li>B</li>
<li>G</li>
</ul>

<table>

<tr>
<td>Alpha1</td>
<td>Some content</td>
</tr>

<tr>
<td>Alpha2</td>
<td>Some content</td>
</tr>

<tr>
<td>Alpha3</td>
<td>Some content</td>
</tr>

</table>

我对 jQuery 真的很陌生,所以任何关于如何解决这样的问题的提示都将不胜感激:)

I'm really new to jQuery so any hint on how to go about a problem like this would be appreciated :)

推荐答案

Sotris 的回答几乎是正确的.我相信你想要的是:

Sotris is almost correct in his answer. I believe that what you want is:

$('li').click(function() {
    var letter = $(this).text();
    $("td").hide();
    $("tr").each(function(){
        if ($("td:first:contains('" + letter + "')", this).length != 0) {
            $('td', this).show();
        }
    })
});

如果您真的只想比较连续第一个TD"的第一个字母,而不是任何字母(:contains"),那么请更改这行说:

If you are really interested only in comparing the first letter of the first "TD" in a row, and not any letter (":contains") then change the line that says:

if ($("td:first:contains('" + letter + "')", this).length != 0) {

作者:

if ($("td:first", this).text().substr(0,1) == letter) {

或者,您可以使用正则表达式,例如替换:

Alternatively you could use a regular expression, e.g. replace:

var letter = $(this).text();

作者:

var re = new RegExp('^' + $(this).text());

还有那句话:

if ($("td:first:contains('" + letter + "')", this).length != 0) {

作者:

if ($("td:first", this).text().match(re)) {

这篇关于根据表格单元格的内容隐藏表格行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆