[英]Jquery selector all cells in table except
我試圖找到正確的選擇器,以便在單擊任何Hello單元格時將背景更改為藍色,但是如果單擊“再見”,則無法將背景更改為藍色。 將類添加到Hello單元格是可能的選擇,但不是首選方法。
$(function() { $('#myTable td').click(function() { $('#myTable').addClass('unfocused'); }); });
.unfocused { background-color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id='myTable'> <tr> <td>Hello</td> </tr> <tr> <td>Hello</td> </tr> <tr> <td>Hello</td> </tr> <tr> <td>Hello</td> </tr> <tr> <td> <table id='otherTable'> <tr> <td>Something</td> </tr> </table> </td> </tr>
我試過了:
$('#myTable td').not('#otherTable td').click(....
$('#myTable td').not('#otherTable').click(....
和那些不工作。
附上一個小提琴。
也許這就是您所需要的。 請參閱下面的演示
有兩個選項。
由於要檢查<th>
的文本內容以執行特定操作,因此可以使用jQuery .text()
獲取<th>
的內容。
您還需要JavaScript的this
指代當前被點擊<th>
。
選項1
單擊此選項時,將一直向所有<th>
添加.unfocused
類。
$(document).ready(function() { $('th').click(function() { if ($(this).text() == "Hello") { $(this).addClass('unfocused'); } }); });
.unfocused { background: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id='myTable'> <tr> <th>Hello</th> </tr> <tr> <th>Hello</th> </tr> <tr> <th>Hello</th> </tr> <tr> <th>Hello</th> </tr> <tr> <th>Hello</th> </tr> <tr> <th>Hello</th> </tr> <tr> <th> <table id='otherTable'> <tr> <th>Goodbye</th> </tr> </table> </th> </tr> <tr> <th>Hello</th> </tr> </table>
選項2
此選項在將.unfocused
類添加到當前單擊的<th>
之前,從所有<th>
刪除.unfocused
類。
$(document).ready(function() { $('th').click(function() { if ($(this).text() == "Hello") { $('th').removeClass('unfocused'); $(this).addClass('unfocused'); } }); });
.unfocused { background: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id='myTable'> <tr> <th>Hello</th> </tr> <tr> <th>Hello</th> </tr> <tr> <th>Hello</th> </tr> <tr> <th>Hello</th> </tr> <tr> <th>Hello</th> </tr> <tr> <th>Hello</th> </tr> <tr> <th> <table id='otherTable'> <tr> <th>Goodbye</th> </tr> </table> </th> </tr> <tr> <th>Hello</th> </tr> </table>
好吧,知道了,我想您正在尋找這樣的東西
https://jsfiddle.net/smqdx20x/
$('#myTable th').not($('th > table#otherTable').parent()).not('table#otherTable th')
您可以使用:contains
選擇器:
$(function() { $('#myTable th:contains(Hello)').click(function() { $('#myTable').addClass('unfocused'); }); });
.unfocused { background-color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table id='myTable'> <tr> <th>Hello</th> </tr> <tr> <th>Hello</th> </tr> <tr> <th>Goodbye</th> </tr> </table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.