开发者

Hide table row based on content of table cell

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.

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.

This is my markup:

<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&开发者_开发百科gt;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>

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>

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


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();
        }
    })
});

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) {

by:

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

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

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

By:

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

and the line that says:

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

by:

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


edit: I hadn't checked that it doesn't show and the second td so I changed a little my code:

 $('li').click(function() {
var letter = $(this).text();
    $("table td").hide();
    $("table td:contains("+letter+"), table td:contains("+letter+") + td").show();
});

Demo: http://jsfiddle.net/rdBx9/1

or

$('li').click(function() {
var letter = $(this).text();
    $("table td").hide();
    $("table td:contains("+letter+")").show().next().show();
});

Demo: http://jsfiddle.net/rdBx9/2

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜