分区中名称前缀的Jquery选择器

Jquery Selectors for name prefixes in division

本文关键字:Jquery 选择器 前缀 分区      更新时间:2023-09-26

在我的HTML代码中,我有4个不同视图的按钮1、2、3和4。我有一些div命名为:

sheet(button id)+some string

因此,假设每当我点击按钮2时,我都希望具有id=sheet2abcid=sheet2xyz等的所有分区都可见,而对于其余分区(即1、3和4),dispaly:none属性应该设置为与sheet1abcsheet3abc等类似。

如何通过jQuery选择器实现这一点?

KISS。本质上:

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

工作示例:http://jsfiddle.net/j4TzA/

我认为您希望在jQuery选择器中使用通配符。

这显示了id以"sheet1"开头的每个div

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

这隐藏了其他:

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

我制作了一把小提琴来证明这一点。

按钮:<a href="1" class="button">button 1</a>

纸张:<div id="sheet1" class="sheet">sheet 1</div>

jQuery:

$('.button').click(function(event){
    event.preventDefault();
    $('.sheet').hide();
    $('#sheet'+$(this).attr('href')).show();
}

下次让你的问题更清楚。

您可以像一样进行过滤

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

然后编码按钮,如:

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