不同元素类型的name属性的jQuery选择器

时间:2012-07-10 18:24:07

标签: jquery jquery-selectors

我有一张行表。在其中一列中,某些行具有带静态文本的跨度,某些行具有可供选择的值的选择。该列中的所有元素都具有相同的名称属性。在我的表单提交中,我遍历行并想要获取所有列的值。我希望有一个jQuery选择器语句来获取该元素的值(span或select,name属性为“materialValue”)。我怎么用jQuery做到这一点?以下是html代码段。

<table>
  <tr><td>
      <span id="materialValue1" name="materialValue>ONE</span>
  </td></tr>
  <tr><td>
      <span id="materialValue2" name="materialValue>TWO</span>
  </td></tr>
  <tr><td>
      <select id="materialValue3" name="materialValue>
        <option>ONE</option>
        <option>TWO</option>
        <option>THREE</option>
      </select>
  </td></tr>
  <tr><td>
      <select id="materialValue4" name="materialValue>
        <option>ONE</option>
        <option>TWO</option>
        <option>THREE</option>
      </select>
  </td></tr>
</table>

编辑:我习惯用元素名称/值指定元素类型然后方括号。我不知道如何在没有元素类型名称的情况下指定jquery选择器。例如$('span[name="materialValue"]', this)。指定$('[name="materialValue"]', this)是否合法?对我来说很奇怪。

2 个答案:

答案 0 :(得分:7)

您只需要一个属性选择器:

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

此外,您在html

中的属性name后缺少结束引号

在此查看参考资料: http://api.jquery.com/attribute-equals-selector/

答案 1 :(得分:4)

喜欢这个......

$("[name=materialValue]")    // Select element with name attribute with a specific value

使用括号选择属性。在其他情况下你也可以像这样使用它......

$("div[id]")      // Select element with an id attribute

$("[name*=test]") // Select all elements with *test* in the name attribute (partial)

等。

相关问题