我有一个表列,我正在尝试展开和隐藏。当我按类而不是按元素名称选择jQuery时,jQuery似乎隐藏了<td>元素。

例如:

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

注意下面的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>

当前回答

您可以使用以下功能:

get.elementbyId();

其他回答

您可以用老式的方式命名元素数组,并将该数组传递给jQuery。

函数toggleByName(){var arrChkBox=文档.getElementsByName(“chName”);$(arrChkBox).tggle();}<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>

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

或者您可以向元素添加另一个类以供选择。(这是我会做的)

函数切换ByClass(bolShow){if(bolShow){$(“.rowToToToggle”).show();}其他{$(“.rowToToToggle”).hide();}}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><html><head><title>sandBox</title></head><body><表><tr><td>数据1</td><td class=“bold rowToToToggle”>data2</td></tr><tr><td>数据1</td><td class=“bold rowToToToggle”>data2</td></tr><tr><td>数据1</td><td class=“bold rowToToToggle”>data2</td></tr></table><input type=“button”onclick=“toggleByClass(true);”value=“show”/><input type=“button”onclick=“toggleByClass(false);”value=“hide”/></body></html>

框架通常以如下形式使用括号名称:

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

我已经这样做了,而且效果很好:

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

https://api.jquery.com/attribute-equals-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'

如果您有以下内容:

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