jQuery match only part of id from div

前端 未结 6 1831
星月不相逢
星月不相逢 2021-02-01 12:51

I ran into an unusual situation yesterday night.

I need to match only part of id. Let me clear you all with an example

I have few divs like



        
相关标签:
6条回答
  • 2021-02-01 13:28

    You could use the "Starts With" selector:

    $('div[id^="sales_info_"]')
    

    I'd rather recommend you use a unique class name for your elements that you can select on though.

    0 讨论(0)
  • 2021-02-01 13:31

    You want the attribute starts with selector:

    $('div[id^="sales_info"]').bind( ... );
    
    0 讨论(0)
  • 2021-02-01 13:38

    You can use css selector

    try this code

    html

    <div id="sales_info_1"></div>
    <div id="user_info_1"></div>
    <div id="sales_info_2"></div>
    <div id="user_info_2"></div>
    <div id="sales_info_3"></div>
    <div id="user_info_3"></div>
    

    css

    .red{
        display:block; 
        float:left; 
        width:50px; 
        height:20px; 
        background-color:#FF0000;}
    .blue{
        display:block; 
        float:left; 
        width:50px; 
        height:20px; 
        background-color:#0000FF;}
    

    jquery

    $('div[id^="sales"]').addClass('red');
    $('div[id^="user"]').addClass('blue');
    

    css selector ^= will select div with ID that start with the specified value and add the css style.

    0 讨论(0)
  • 2021-02-01 13:41

    Alternatively, add class="sales_info" to your HTML mark-up.

    Then, do this:

    $(".sales_info").bind("click", function() {
       ...
    }
    
    0 讨论(0)
  • 2021-02-01 13:47

    Try with this

    $("div[id^='sales_info_']").bind( ... );
    
    0 讨论(0)
  • 2021-02-01 13:48

    I actually needed the end-with effect and found it here. It's easily used as follows:

    <script>
    $( "input[name$='letter']" ).val( "a letter" );
    </script>
    

    You just replace the ^ with $ in the selector.

    0 讨论(0)
提交回复
热议问题