How can I select an element by name with jQuery?

前端 未结 14 2524
迷失自我
迷失自我 2020-11-22 05:13

Have a table column I\'m trying to expand and hide:

jQuery seems to hide the td elements when I select it by class but not by element\'s name.

<
相关标签:
14条回答
  • 2020-11-22 05:41

    You can use any attribute as selector with [attribute_name=value].

    $('td[name=tcol1]').hide();
    
    0 讨论(0)
  • 2020-11-22 05:46

    Personally, what I've done in the past is give them a common class id and used that to select them. It may not be ideal as they have a class specified that may not exist, but it makes the selection a hell of a lot easier. Just make sure you're unique in your classnames.

    i.e. for the example above I'd use your selection by class. Better still would be to change the class name from bold to 'tcol1', so you don't get any accidental inclusions into the jQuery results. If bold does actually refer to a CSS class, you can always specify both in the class property - i.e. 'class="tcol1 bold"'.

    In summary, if you can't select by Name, either use a complicated jQuery selector and accept any related performance hit or use Class selectors.

    You can always limit the jQuery scope by including the table name i.e. $('#tableID > .bold')

    That should restrict jQuery from searching the "world".

    Its could still be classed as a complicated selector, but it quickly constrains any searching to within the table with the ID of '#tableID', so keeps the processing to a minimum.

    An alternative of this if you're looking for more than 1 element within #table1 would be to look this up separately and then pass it to jQuery as this limits the scope, but saves a bit of processing to look it up each time.

    var tbl = $('#tableID');
    var boldElements = $('.bold',tbl);
    var rows = $('tr',tbl);
    if (rows.length) {
       var row1 = rows[0]; 
       var firstRowCells = $('td',row1); 
    }
    
    0 讨论(0)
  • 2020-11-22 05:47

    You can use the jQuery attribute selector:

    $('td[name ="tcol1"]')   // matches exactly 'tcol1'
    $('td[name^="tcol"]' )   // matches those that begin with 'tcol'
    $('td[name$="tcol"]' )   // matches those that end with 'tcol'
    $('td[name*="tcol"]' )   // matches those that contain 'tcol'
    
    0 讨论(0)
  • 2020-11-22 05:47

    Frameworks usually use bracket names in forms, like:

    <input name=user[first_name] />
    

    They can be accessed by:

    // in JS:
    this.querySelectorAll('[name="user[first_name]"]')
    
    // in jQuery:
    $('[name="user[first_name]"]')
    
    // or by mask with escaped quotes:
    this.querySelectorAll("[name*=\"[first_name]\"]")
    
    0 讨论(0)
  • 2020-11-22 05:49

    I've done like this and it works:

    $('[name="tcol1"]')
    

    https://api.jquery.com/attribute-equals-selector/

    0 讨论(0)
  • 2020-11-22 05:50

    Here's a simple solution: $('td[name=tcol1]')

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