0

对不起这个古怪的标题,这里是例子:

<table>
  <tr>
    <th class="hey-1-aa"></th>
  </tr>
  <tr>
    <th class="hey-2-aa"></th>
  </tr>
  <tr>
    <td class="hey-1-bb"></tr>
  </tr>
  <tr>
    <td class="hey-2-bb"></tr>
  </tr>
</table>

有没有更好的方法来选择所有以类前缀“hey-2-”开头的 THs/TRs,而不是冗长的东西$('th[class^="hey-2"], td[class^="hey-2"]')

4

4 回答 4

2

$('.hey-2')

the selectors for sizzle (the jquery selector engine) begin with basic css and then move from there. so if you can style an element with a selector, you can grab it from jquery the same way.

for a list of selectors take a look at the jquery api

EDIT

so i would think the first thing to eliminate is limiting it to tr/th and just doing something like

$('table [class^=hey-2]')

that simplifies it quite a bit.

i tend to agree with the other answers though. if the items legitimately have something in common, why not give them a common class? instead of class="hey-2-aa" make it class="hey-2 aa" then you really can just use the original answer i posted.

于 2012-07-26T03:08:11.103 回答
1

请记住,您可以为一个元素使用多个类。因此,也许为元素设置更多类会很有用。选择起来会更简单。

于 2012-07-26T03:11:00.823 回答
1
<table>
  <tr>
    <th class="hey-1-aa"></th>
  </tr>
  <tr>
    <th class="hey-2-aa sameclass"></th>
  </tr>
  <tr>
    <td class="hey-1-bb"></tr>
  </tr>
  <tr>
    <td class="hey-2-bb sameclass"></tr>
  </tr>
</table>

$(".sameclass");
于 2012-07-26T03:16:18.030 回答
0

你可以试试这个:

$('tr > [class^="hey-2"]')

也就是说,选择每个 tr 元素的任何具有以“hey-2”开头的类的子元素。

演示:http: //jsfiddle.net/CCuxX/

(或者对于问题中的标记完全一样$('tr:odd > *'):)

我知道显然您已经简化了问题的标记,但就目前而言,您似乎将类用作唯一标识符 - 如果是这样,您应该使用 ids。

于 2012-07-26T03:38:04.020 回答