开发者

Jquery Selectors for name prefixes in division

In my 开发者_运维知识库HTML code I have buttons 1, 2, 3 and 4 for 4 different views. I have some divs named as:

sheet(button id)+some string

So whenever I click on button 2 suppose, I want all the divisions with id=sheet2abc, id=sheet2xyz, etc to become visible and for the rest (i.e. 1, 3 and 4) the dispaly:none property should be set like for sheet1abc, sheet3abc, etc.

How can I do this via jQuery selectors?


KISS. Essentially:

$('[id^=sheet]').hide();
$('[id^=sheet'+num+']').show(); // num is a relevant value, see the example

Working example: http://jsfiddle.net/j4TzA/


I think you want to use wildcards in jQuery selectors.

This shows every div whose id starts with "sheet1":

$('div[id^=sheet1]').each(function() {
    $(this).show();
});

And this hides the others:

$('div[id^=sheet]:not([id^=sheet1])').each(function() {
    $(this).hide();
});

I created a fiddle to demonstrate that.


Buttons: <a href="1" class="button">button 1</a> and so on

Sheets: <div id="sheet1" class="sheet">sheet 1</div> and so on

jQuery:

$('.button').click(function(event){

    event.preventDefault();

    $('.sheet').hide();
    $('#sheet'+$(this).attr('href')).show();

}

Next time make your question more clear.


You can filter like:

$('button').click(function() {
    var $button = $(this);
    $('div[id^=sheet]').each(function() {
        if((new RegExp("^sheet" + $button.data('id') + ".*$")).test($(this).attr('id'))) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
});

Then code buttons like:

<button data-id="1">1</button>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜