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

时间:2021-09-20 04:51:32

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.

当我按类而不是按元素名选择td元素时,jQuery似乎隐藏了td元素。

For example, why does:

例如,为什么:

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

Note the HTML below, the second column has the same name for all rows. How could I create this collection using the name attribute?

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

15 个解决方案

#1


1786  

You can use the 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'

#2


163  

Any attribute can be selected using [attribute_name=value] way. See the sample here:

可以使用[attribute_name=value]方式选择任何属性。看到这里的示例:

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

#3


51  

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

#4


22  

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.

注意:您唯一有理由使用“name”属性的时间应该是复选框或单选输入。

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>

#5


18  

You can get the name value from an input field using name element in jQuery by:

您可以使用jQuery中的name元素从输入字段获得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>

#6


13  

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

#7


12  

I've done like this and it works:

我已经这样做了,它是有效的:

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

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

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

#8


5  

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

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

#9


3  

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

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

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

#10


2  

You can get the element in JQuery by using its ID attribute like this:

您可以使用JQuery的ID属性获取该元素,如下所示:

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

#11


2  

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="text" name="chName"/><br />
    <input type="text" name="chName"/><br />
    <input type="text" name="chName"/><br />
    <input type="text" name="chName"/><br />
    <input type="button" onclick="toggleByName();" value="toggle"/>
  </body>
</html>

#12


2  

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.

就我个人而言,我过去所做的是给它们一个公共类id并使用它来选择它们。它可能不理想,因为它们有一个可能不存在的类,但是它使选择变得更加容易。确保你的类名是唯一的。

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

例如,对于上面的例子,我将按类使用你的选择。更好的方法是将类名从粗体更改为“tcol1”,这样就不会在jQuery结果中意外包含任何内容。如果bold确实指的是CSS类,那么可以在class属性中同时指定这两个属性——例如。'类=“tcol1大胆”。

In summary, 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 i.e. $('#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.

它仍然可以被归类为一个复杂的选择器,但是它会快速地限制任何以'#tableID' ID在表中的搜索,因此将处理保持在最小。

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中查找多于一个元素,另一种方法是分别查找,然后将其传递给jQuery,因为这限制了范围,但是每次查找时节省了一些处理。

var tbl = $('#tableID');
var boldElements = $('.bold',tbl);
var rows = $('tr',tbl);
if (rows.length) {
   var row1 = rows[0]; 
   var firstRowCells = $('td',row1); 
}

#13


1  

To hide all td which has name "tcol1"

隐藏所有名为“tcol1”的td

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

#14


1  

You forgot the second set of quotes, which makes the accepted answer incorrect:

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

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

#15


-2  

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

这是有用的代码。

#1


1786  

You can use the 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'

#2


163  

Any attribute can be selected using [attribute_name=value] way. See the sample here:

可以使用[attribute_name=value]方式选择任何属性。看到这里的示例:

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

#3


51  

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

#4


22  

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.

注意:您唯一有理由使用“name”属性的时间应该是复选框或单选输入。

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>

#5


18  

You can get the name value from an input field using name element in jQuery by:

您可以使用jQuery中的name元素从输入字段获得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>

#6


13  

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

#7


12  

I've done like this and it works:

我已经这样做了,它是有效的:

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

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

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

#8


5  

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

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

#9


3  

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

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

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

#10


2  

You can get the element in JQuery by using its ID attribute like this:

您可以使用JQuery的ID属性获取该元素,如下所示:

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

#11


2  

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="text" name="chName"/><br />
    <input type="text" name="chName"/><br />
    <input type="text" name="chName"/><br />
    <input type="text" name="chName"/><br />
    <input type="button" onclick="toggleByName();" value="toggle"/>
  </body>
</html>

#12


2  

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.

就我个人而言,我过去所做的是给它们一个公共类id并使用它来选择它们。它可能不理想,因为它们有一个可能不存在的类,但是它使选择变得更加容易。确保你的类名是唯一的。

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

例如,对于上面的例子,我将按类使用你的选择。更好的方法是将类名从粗体更改为“tcol1”,这样就不会在jQuery结果中意外包含任何内容。如果bold确实指的是CSS类,那么可以在class属性中同时指定这两个属性——例如。'类=“tcol1大胆”。

In summary, 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 i.e. $('#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.

它仍然可以被归类为一个复杂的选择器,但是它会快速地限制任何以'#tableID' ID在表中的搜索,因此将处理保持在最小。

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中查找多于一个元素,另一种方法是分别查找,然后将其传递给jQuery,因为这限制了范围,但是每次查找时节省了一些处理。

var tbl = $('#tableID');
var boldElements = $('.bold',tbl);
var rows = $('tr',tbl);
if (rows.length) {
   var row1 = rows[0]; 
   var firstRowCells = $('td',row1); 
}

#13


1  

To hide all td which has name "tcol1"

隐藏所有名为“tcol1”的td

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

#14


1  

You forgot the second set of quotes, which makes the accepted answer incorrect:

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

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

#15


-2  

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

这是有用的代码。