简体   繁体   English

如何使用 jQuery 按名称选择元素?

[英]How can I select an element by name with jQuery?

I 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 the element's name .当我按class而不是按元素name选择 jQuery 时,它似乎隐藏了<td>元素。

For example:例如:

$(".bold").hide(); // Selecting by class works.
$("tcol1").hide(); // Selecting by name does not work.

Note the HTML below.请注意下面的 HTML。 The second column has the same name for all rows.第二列的所有行都具有相同的name How could I create this collection using the name attribute?我如何使用name属性创建这个集合?

<tr>
  <td>data1</td>
  <td name="tcol1" class="bold"> data2</td>
</tr>
<tr>
  <td>data1</td>
  <td name="tcol1" class="bold"> data2</td>
</tr>
<tr>
  <td>data1</td>
  <td name="tcol1" class="bold"> data2</td>
</tr>

You can use the jQuery attribute selector :您可以使用jQuery 属性选择器

$('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'

Any attribute can be selected using [attribute_name=value] way.可以使用[attribute_name=value]方式选择任何属性。 See the sample here :此处查看示例:

var value = $("[name='nameofobject']");

If you have something like:如果你有类似的东西:

<input type="checkbox" name="mycheckbox" value="11" checked="">
<input type="checkbox" name="mycheckbox" value="12">

You can read all like this:你可以这样阅读:

jQuery("input[name='mycheckbox']").each(function() {
    console.log( this.value + ":" + this.checked );
});

The snippet:片段:

 jQuery("input[name='mycheckbox']").each(function() { console.log( this.value + ":" + this.checked ); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="mycheckbox" value="11" checked=""> <input type="checkbox" name="mycheckbox" value="12">

You could get the array of elements by name the old fashioned way and pass that array to jQuery.您可以通过老式的方式按名称获取元素数组并将该数组传递给 jQuery。

 function toggleByName() { var arrChkBox = document.getElementsByName("chName"); $(arrChkBox).toggle(); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <title>sandBox</title> </head> <body> <input type="radio" name="chName"/><br /> <input type="radio" name="chName"/><br /> <input type="radio" name="chName"/><br /> <input type="radio" name="chName"/><br /> <input type="button" onclick="toggleByName();" value="toggle"/> </body> </html>

note: the only time you would have a reason to use the "name" attribute should be for checkbox or radio inputs.注意:您唯一有理由使用“名称”属性的应该是复选框或无线电输入。

Or you could just add another class to the elements for selection.(This is what I would do)或者您可以向元素添加另一个类以供选择。(这就是我会做的)

 function toggleByClass(bolShow) { if (bolShow) { $(".rowToToggle").show(); } else { $(".rowToToggle").hide(); } }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <title>sandBox</title> </head> <body> <table> <tr> <td>data1</td> <td class="bold rowToToggle">data2</td> </tr> <tr> <td>data1</td> <td class="bold rowToToggle">data2</td> </tr> <tr> <td>data1</td> <td class="bold rowToToggle">data2</td> </tr> </table> <input type="button" onclick="toggleByClass(true);" value="show"/> <input type="button" onclick="toggleByClass(false);" value="hide"/> </body> </html>

You can get the name value from an input field using name element in jQuery by:您可以通过以下方式使用 jQuery 中的名称元素从输入字段中获取名称值:

 var firstname = jQuery("#form1 input[name=firstname]").val(); //Returns ABCD var lastname = jQuery("#form1 input[name=lastname]").val(); //Returns XYZ console.log(firstname); console.log(lastname);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="form1" id="form1"> <input type="text" name="firstname" value="ABCD"/> <input type="text" name="lastname" value="XYZ"/> </form>

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]\"]")

I've done like this and it works:我这样做了并且有效:

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

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

You forgot the second set of quotes, which makes the accepted answer incorrect:您忘记了第二组引号,这使得接受的答案不正确:

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

Here's a simple solution: $('td[name=tcol1]')这是一个简单的解决方案: $('td[name=tcol1]')

You can use any attribute as selector with [attribute_name=value] .您可以将任何属性用作带有[attribute_name=value]的选择器。

$('td[name=tcol1]').hide();

Performance表现

Today (2020.06.16) I perform tests for chosen solutions on MacOs High Sierra on Chrome 83.0, Safari 13.1.1 and Firefox 77.0.今天(2020.06.16)我在 Chrome 83.0、Safari 13.1.1 和 Firefox 77.0 上对 MacOs High Sierra 上的选定解决方案进行了测试。

Conclusions结论

Get elements by name按名称获取元素

  • getElementByName (C) is fastest solution for all browsers for big and small arrays - however I is probably some kind of lazy-loading solution or It use some internal browser hash-cache with name-element pairs getElementByName (C) 是所有浏览器对于大小数组最快的解决方案——但是我可能是某种延迟加载解决方案或者它使用一些带有名称元素对的内部浏览器哈希缓存
  • mixed js-jquery solution (B) is faster than querySelectorAll (D) solution js-jquery混合方案(B)比querySelectorAll (D)方案快
  • pure jquery solution (A) is slowest纯 jquery 解决方案 (A) 是最慢的

Get rows by name and hide them (we exclude precalculated native solution (I) - theoretically fastest) from comparison - it is used as reference)按名称获取行并隐藏它们(我们从比较中排除预先计算的本机解决方案(I) - 理论上最快) - 它用作参考)

  • surprisingly the mixed js-jquery solution (F) is fastest on all browsers令人惊讶的是,混合 js-jquery 解决方案 (F) 在所有浏览器上都是最快的
  • surprisingly the precalculated solution (I) is slower than jquery (E,F) solutions for big tables (.!!) - I check that .hide() jQuery method set style "default:none" on hidden elements - but it looks that they find faster way of do it than element.style.display='none'令人惊讶的是,预先计算的解决方案 (I) 比大表 (.!!) 的 jquery (E,F) 解决方案慢 - 我检查了 .hide() jQuery 方法在隐藏元素上设置样式"default:none" - 但看起来他们找到了比element.style.display='none'更快的方法
  • jquery (E) solution is quite-fast on big tables jquery (E) 解决方案在大表上相当快
  • jquery (E) and querySelectorAll (H) solutions are slowest for small tables jquery (E) 和 querySelectorAll (H) 解决方案对于小表来说最慢
  • getElementByName (G) and querySelectorAll (H) solutions are quite slow for big tables getElementByName (G) 和 querySelectorAll (H) 解决方案对于大表来说相当慢

在此处输入图像描述

Details细节

I perform two tests for read elements by name ( A , B , C , D ) and hide that elements (E,F,G,H,I)我按名称( ABCD )对读取元素执行两个测试并隐藏该元素(E、F、G、H、I)

  • small table - 3 rows - you can run test HERE小桌子 - 3 行 - 你可以在这里运行测试
  • big table - 1000 rows - you can run test HERE大表 - 1000 行 - 你可以在这里运行测试

Snippet below presents used codes下面的片段展示了使用过的代码

 //https://stackoverflow.com/questions/1107220/how-can-i-select-an-element-by-name-with-jquery# // https://jsbench.me/o6kbhyyvib/1 // https://jsbench.me/2fkbi9rirv/1 function A() { return $('[name=tcol1]'); } function B() { return $(document.getElementsByName("tcol1")) } function C() { return document.getElementsByName("tcol1") } function D() { return document.querySelectorAll('[name=tcol1]') } function E() { $('[name=tcol1]').hide(); } function F() { $(document.getElementsByName("tcol1")).hide(); } function G() { document.getElementsByName("tcol1").forEach(e=>e.style.display='none'); } function H() { document.querySelectorAll('[name=tcol1]').forEach(e=>e.style.display='none'); } function I() { let elArr = [...document.getElementsByName("tcol1")]; let length = elArr.length for(let i=0; i<length; i++) elArr[i].style.display='none'; } // ----------- // TEST // ----------- function reset() { $('td[name=tcol1]').show(); } [A,B,C,D].forEach(f=> console.log(`${f.name} rows: ${f().length}`));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <div>This snippet only presents used codes</div> <table> <tr> <td>data1</td> <td name="tcol1" class="bold"> data2</td> </tr> <tr> <td>data1</td> <td name="tcol1" class="bold"> data2</td> </tr> <tr> <td>data1</td> <td name="tcol1" class="bold"> data2</td> </tr> </table> <button onclick="E()">E: hide</button> <button onclick="F()">F: hide</button> <button onclick="G()">G: hide</button> <button onclick="H()">H: hide</button> <button onclick="I()">I: hide</button><br> <button onclick="reset()">reset</button>

Example results on Chrome Chrome 上的示例结果

在此处输入图像描述

Personally, what I've done in the past is give them a common class id and used that to select them.就个人而言,我过去所做的是给他们一个通用的类 ID 并用它来选择它们。 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.只要确保你的类名是独一无二的。

ie 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.更好的做法是将类名从粗体更改为“tcol1”,这样您就不会在 jQuery 结果中意外包含任何内容。 If bold does actually refer to a CSS class, you can always specify both in the class property - ie 'class="tcol1 bold"'.如果 bold 实际上指的是一个 CSS 类,您总是可以在类属性中指定两者 - 即 '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.总之,如果您不能按名称选择,要么使用复杂的 jQuery 选择器并接受任何相关的性能影响,要么使用类选择器。

You can always limit the jQuery scope by including the table name ie $('#tableID >.bold')您始终可以通过包含表名来限制 jQuery 范围,即 $('#tableID >.bold')

That should restrict jQuery from searching the "world".这应该限制 jQuery 搜索“世界”。

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.它仍然可以被归类为一个复杂的选择器,但它很快将任何搜索限制在 ID 为“#tableID”的表内,因此将处理过程保持在最低限度。

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.如果您在 #table1 中查找超过 1 个元素,则另一种方法是单独查找,然后将其传递给 jQuery,因为这限制了范围,但每次都节省了一些处理时间来查找它。

var tbl = $('#tableID');
var boldElements = $('.bold',tbl);
var rows = $('tr',tbl);
if (rows.length) {
   var row1 = rows[0]; 
   var firstRowCells = $('td',row1); 
}
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    var a= $("td[name=tcol3]").html();
    alert(a);

});

</script>


<table border="3">
<tr>    
    <td>data1</td>
    <td name="tcol1" class="bold"> data2tcol1</td>
</tr>
<tr>    
    <td>data1</td>
    <td name="tcol2" class="bold"> data2tcol2</td>
</tr>  
<tr>    
    <td>data1</td>
    <td name="tcol3" class="bold"> data2tcol3</td>
</tr>
</table>

This is the Code which can be helpful. 这是可能有用的代码。

You can get the element in JQuery by using its ID attribute like this:您可以使用其 ID 属性在 JQuery 中获取该元素,如下所示:

$("#tcol1").hide();

You can use the function:您可以使用以下功能:

get.elementbyId();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM