选择具有复杂ID模式的元素

时间:2022-09-11 21:48:46

I have set of buttons like this:

我有这样的按钮设置:

<button id="grid1_createBtn">Create</button>
<button id="grid1_updateBtn">Update</button>
<button id="grid2_createBtn">Create</button>
...

These button does not have any class, so I need to select them via their ID. The "grid" part of id is static and same for all buttons. I found this answer, but I don't want to use ​$("[id^=grid]"), because may be some other other element with starting id "grid" exist. Can anyone help me?

这些按钮没有任何类,所以我需要通过他们的ID选择它们。 id的“网格”部分是静态的,并且对于所有按钮都是相同的。我找到了这个答案,但我不想使用$(“[id ^ = grid]”),因为可能是其他一些起始id为“grid”的元素存在。谁能帮我?

4 个解决方案

#1


6  

To select the buttons with a regular expression, you may use filter like this :

要选择带有正则表达式的按钮,您可以使用如下过滤器:

$('button').filter(function(){
    return /^grid\d+_\w+Btn$/.test(this.id)
})

#2


0  

Try this:

尝试这个:

var id= 1;
$("button[id*='grid" + id+ "_createBtn']");

#3


0  

You may also combine attribute selectors like below as long as all your buttons start with grid and end with Btn.

只要所有按钮都以网格开头并以Btn结尾,您也可以组合下面的属性选择器。

$('button[id^="grid"][id$="Btn"]')

-A Demo-

-A演示 -

#4


0  

You can combine!

你可以结合!

$("[id^='grid'][id$='Btn']")

$("[id^='grid'][id$='Btn'][id*='_']")

or you can mix with Denis Seguret aproach

或者你可以混合使用Denis Seguret aproach

$("button[id^='grid']").filter( 
    function(){
        return /^grid\d+_(create|update)Btn$/.test(this.id);
    }
)

this is faster than only the filter.

这比仅过滤器更快。

#1


6  

To select the buttons with a regular expression, you may use filter like this :

要选择带有正则表达式的按钮,您可以使用如下过滤器:

$('button').filter(function(){
    return /^grid\d+_\w+Btn$/.test(this.id)
})

#2


0  

Try this:

尝试这个:

var id= 1;
$("button[id*='grid" + id+ "_createBtn']");

#3


0  

You may also combine attribute selectors like below as long as all your buttons start with grid and end with Btn.

只要所有按钮都以网格开头并以Btn结尾,您也可以组合下面的属性选择器。

$('button[id^="grid"][id$="Btn"]')

-A Demo-

-A演示 -

#4


0  

You can combine!

你可以结合!

$("[id^='grid'][id$='Btn']")

$("[id^='grid'][id$='Btn'][id*='_']")

or you can mix with Denis Seguret aproach

或者你可以混合使用Denis Seguret aproach

$("button[id^='grid']").filter( 
    function(){
        return /^grid\d+_(create|update)Btn$/.test(this.id);
    }
)

this is faster than only the filter.

这比仅过滤器更快。