bar*_*uck 5 html javascript css jquery
我试图找到正确的选择器,以便在单击任何Hello单元格时将背景更改为蓝色,但如果单击Goodbye则不能.将类添加到Hello单元是一种可能的选择,但不是首选.
$(function() {
$('#myTable td').click(function() {
$('#myTable').addClass('unfocused');
});
});Run Code Online (Sandbox Code Playgroud)
.unfocused {
background-color: blue;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
我试过了:
$('#myTable td').not('#otherTable td').click(....
$('#myTable td').not('#otherTable').click(....
Run Code Online (Sandbox Code Playgroud)
而那些不工作.
附上一个小提琴.
也许这就是你需要的.见下面的演示
有两种选择.
由于您正在检查文本内容<th>以执行特定操作,因此您可以使用jQuery .text()来获取内容<th>.
您还需要JavaScript this来引用当前点击的内容<th>.
选项1
单击时,此选项会继续向.unfocused所有人添加类<th>.
$(document).ready(function() {
$('th').click(function() {
if ($(this).text() == "Hello") {
$(this).addClass('unfocused');
}
});
});Run Code Online (Sandbox Code Playgroud)
.unfocused {
background: blue;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
选项2
在将类添加到当前单击之前,此选项.unfocused将从中删除所有类.<th>.unfocused<th>
$(document).ready(function() {
$('th').click(function() {
if ($(this).text() == "Hello") {
$('th').removeClass('unfocused');
$(this).addClass('unfocused');
}
});
});Run Code Online (Sandbox Code Playgroud)
.unfocused {
background: blue;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
小智 1
好的,明白了,我想您正在寻找类似的东西
https://jsfiddle.net/smqdx20x/
$('#myTable th').not($('th > table#otherTable').parent()).not('table#otherTable th')
Run Code Online (Sandbox Code Playgroud)