Can this jQuery code snippet be shortened?

后端 未结 1 1444
被撕碎了的回忆
被撕碎了的回忆 2021-02-07 02:06

I have just started using jQuery and although following code gets the job done, I have a feeling that it can be shortened.

var accountAddress = $(document.create         


        
相关标签:
1条回答
  • 2021-02-07 02:34

    Yes, it can.

    $('#customerid_c').nextAll().eq(2)
        .append('<input class="readOnly" id="d_accountAddress" />');
    

    In jQuery 1.4.2, you can write

    $('#customerid_c~:eq(2)')
        .append('<input class="readOnly" id="d_accountAddress" />');
    

    This selector, which does not work correctly in earlier versions of jQuery, uses the Next Siblings Selector (~) to select all sibling elements following #customerid_c, then uses the :eq selector to select the third (zero-based) element matched by the other selector.

    jQuery has a large variety of selectors that can probably replace the indexed sibling. If you show us your HTML, we can find you one.

    Other notes:

    You can set multiple attributes in one call:

    $(something).attr({ id: 'd_accountAddress', type: 'text' });
    
    0 讨论(0)
提交回复
热议问题