簡體   English   中英

如何使用正則表達式使用jQuery通過ID選擇元素?

[英]How can I select an element by ID with jQuery using regex?

我有以下輸入元素:

<input id="AAA_RandomString_BBB" type="text" />
<input id="AAA_RandomString_BBB_Start" type="text" />
<input id="AAA_RandomString_BBB_End" type="text" />

AAA和BBB是常數,我將永遠知道它們是什么。 但是RandomString總是隨機的。

我想獲得AAA_RandomString_BBB的值。 我不希望輸入元素的值以_Start或_End結尾的ID結尾。

我嘗試了以下內容:

$('[id^="AAA_"]')

但是上面選擇了所有ID為“AAA_”的輸入元素

我需要一些方法來選擇使用正則表達式類型的語法,如:

$('[id^="AAA_(.+?)_BBB"]')

這可能嗎? 如果沒有,任何人都可以提出一種選擇方法

您可以在多屬性選擇器中組合兩個選擇

​$("[id^=AAA_][id$=_BBB]")

它將返回與所有指定屬性過濾器匹配的所有元素:


另一種通用替代品

用這個:

$('[id^="AAA_"][id$="_BBB"]')

小提琴: http//jsfiddle.net/J6hGx/

您可以查找從AAA開始並以BBB結尾的id,如下所示:

​$("[id^=AAA_][id$=_BBB]")

工作小提琴: http//jsfiddle.net/DN9uV/

這可以這樣做:

$('input').filter(function(){ return this.id.match(/^AAA_.+_BBB$/) })

您可以使用$('input', <context>)來使搜索更精確。 另見這里

我用類別選擇器來解決這個問題,這些選擇器不需要是唯一的。

這對速度也有積極的影響,因為不需要復雜的搜索。此外,您可以將其用於不同元素的不同樣式

例如

<elem id="1" class="aa">element type aa</elem>
<elem id="2" class="aa">element type aa</elem>
<elem id="3" class="aa bb">element type aa and bb</elem>
<elem id="4" class="bb">element type bb</elem>

現在您可以簡單地使用類選擇器

$('.aa').click(function(){
     console.log( 'clicked type aa #' + $(this).attr('id') );
});

$('.bb').click(function(){
     console.log( 'clicked type bb #' + $(this).attr('id') );
});

最好只檢查_BBB上的id結尾

 $("[id$=_BBB]")

這個怎么樣 :

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    </head>
    <body>
        <input id="AAA_RandomString_BBB" type="text" />
        <input id="AAA_RandomString_BBB_Start" type="text" />
        <input id="AAA_RandomString_BBB_End" type="text" />

        <script>
            $(document).ready(function () {
                debugger
                var targetElement = $('input')
                .filter(function () {
                    var el = this.id.match(/^AAA.*BBB$/g);
                    return el;
                });
                console.log(targetElement.val());
            })
        </script>
    </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM