1438

我有一个表格列,我正在尝试展开和隐藏。当我<td>通过class而不是通过元素的name.

例如:

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

请注意下面的 HTML。第二列name对所有行都相同。如何使用该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>
4

14 回答 14

2544

您可以使用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'
于 2009-07-10T01:21:08.113 回答
291

可以使用[attribute_name=value]方式选择任何属性。请参阅此处的示例:

var value = $("[name='nameofobject']");
于 2013-09-22T19:07:44.267 回答
78

如果你有类似的东西:

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

你可以这样阅读:

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

片段:

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">

于 2014-07-09T18:34:15.283 回答
29

You could get the array of elements by name the old fashioned way and pass that array to 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>

于 2009-07-11T05:25:01.580 回答
28

您可以使用 jQuery 中的 name 元素从输入字段中获取名称值,方法是:

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>

于 2015-06-15T05:52:03.383 回答
19

框架通常在表单中使用括号名称,例如:

<input name=user[first_name] />

它们可以通过以下方式访问:

// 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]\"]")
于 2015-10-16T16:27:15.793 回答
15

我已经这样做了,它的工作原理:

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

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

于 2015-03-25T20:27:52.180 回答
10

您忘记了第二组引号,这使得接受的答案不正确:

$('td[name="tcol1"]') 
于 2017-11-20T19:27:54.383 回答
5

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

于 2016-04-27T18:47:53.033 回答
4

您可以使用任何属性作为选择器[attribute_name=value]

$('td[name=tcol1]').hide();
于 2016-03-31T12:51:10.637 回答
3

表现

今天(2020.06.16)我在 Chrome 83.0、Safari 13.1.1 和 Firefox 77.0 上对 MacOs High Sierra 上的所选解决方案进行了测试。

结论

按名称获取元素

  • getElementByName(C) 对于大小数组的所有浏览器来说是最快的解决方案 - 但是我可能是某种延迟加载解决方案,或者它使用一些带有名称-元素对的内部浏览器哈希缓存
  • 混合js-jquery解决方案(B)比querySelectorAll(D)解决方案快
  • 纯jquery解决方案(A)最慢

按名称获取行并隐藏它们(我们从比较中排除预先计算的本机解决方案(I) - 理论上最快) - 它用作参考)

  • 令人惊讶的是,混合 js-jquery 解决方案 (F) 在所有浏览器上都是最快的
  • 令人惊讶的是,预先计算的解决方案 (I) 比用于大表的 jquery (E,F) 解决方案慢 (!!!) - 我检查了"default:none"隐藏元素上的 .hide() jQuery 方法设置样式 - 但看起来他们找到了更快的方法比做element.style.display='none'
  • jquery (E) 解决方案在大表上非常快
  • jquery (E) 和 querySelectorAll (H) 解决方案对于小表最慢
  • getElementByName (G) 和 querySelectorAll (H) 解决方案对于大表来说非常慢

在此处输入图像描述

细节

我对按名称( ABCD )读取的元素执行两个测试并隐藏该元素(E,F,G,H,I)

下面的片段显示了使用的代码

//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>

Chrome 上的示例结果

在此处输入图像描述

于 2020-06-16T20:33:17.523 回答
2

就个人而言,我过去所做的就是给他们一个通用的类 id 并用它来选择它们。这可能并不理想,因为他们指定了一个可能不存在的类,但它使选择变得容易得多。只要确保你的类名是独一无二的。

即,对于上面的示例,我将按类别使用您的选择。最好将类名从粗体更改为“tcol1”,这样您就不会意外包含到 jQuery 结果中。如果粗体实际上确实引用了一个 CSS 类,您总是可以在类属性中同时指定这两者 - 即 'class="tcol1 bold"'。

总之,如果您不能按名称选择,请使用复杂的 jQuery 选择器并接受任何相关的性能损失,或者使用类选择器。

您始终可以通过包含表名来限制 jQuery 范围,即 $('#tableID > .bold')

这应该限制 jQuery 搜索“世界”。

它仍然可以归类为复杂的选择器,但它很快将任何搜索限制在 ID 为“#tableID”的表内,因此将处理保持在最低限度。

如果您要在 #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); 
}
于 2015-02-23T12:16:59.950 回答
-2

您可以通过使用它的 ID 属性来获取 JQuery 中的元素,如下所示:

$("#tcol1").hide();
于 2009-07-10T01:09:39.187 回答
-21

您可以使用以下功能:

get.elementbyId();
于 2019-06-19T07:08:53.600 回答