我想要一个项目列表,其中所选元素的颜色在选中时变为红色,所有其他div变为蓝色。如何识别随后变为红色的所选div?
$(document).ready(function() {
$('#table_1 .tableRow div').click(function(event) {
//Set the style for all divs
var myElements = document.querySelectorAll("#table_1 .tableRow div");
for (var i = 0; i < myElements.length; i++) {
myElements[i].className = "blueText";
}
//Set the style for tyhe selected div
//selectedItem.className="selectedText";
});
});
.selectedText {
color: red;
}
.blueText {
color: blue;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id="table_1" class="table">
<div class="tableRow">
<div>
Line 1
</div>
<div>
Line 2
</div>
<div>
Line 3
</div>
</div>
</div>
</body>
</html>
答案 0 :(得分:3)
你可以这样做:
.selectedText {
color: red;
}
.blueText {
color: blue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_1" class="table">
<div class="tableRow">
<div>
Line 1
</div>
<div>
Line 2
</div>
<div>
Line 3
</div>
</div>
</div>
&#13;
Private Sub LinkTest_Click()
Link = "http://tinyhousetalk.com/"
On Error GoTo NoCanDo
ActiveWorkbook.FollowHyperlink Address:=Link, NewWindow:=True
Unload Me
Exit Sub
NoCanDo:
MsgBox "Cannot open " & Link
End Sub
&#13;
答案 1 :(得分:3)
足以改变:
//selectedItem.className="selectedText";
为:
event.target.className="selectedText";
摘录:
$(document).ready(function(){
$('#table_1 .tableRow div').click(function(event) {
//Set the style for all divs
var myElements = document.querySelectorAll("#table_1 .tableRow div");
for (var i = 0; i < myElements.length; i++) {
myElements[i].className="blueText";
}
//Set the style for tyhe selected div
event.target.className="selectedText";
});
});
&#13;
.selectedText {
color: red;
}
.blueText {
color: blue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_1" class="table">
<div class="tableRow">
<div>
Line 1
</div>
<div >
Line 2
</div>
<div >
Line 3
</div>
</div>
</div>
&#13;
答案 2 :(得分:2)
使用tabindex和:focus选择器进行DIV的纯CSS解决方案。
div:focus {
color: red;
}
div {
color: blue;
}
&#13;
<div id="table_1" class="table">
<div class="tableRow">
<div tabindex="1">Line 1</div>
<div tabindex="2">Line 2</div>
<div tabindex="3">Line 3</div>
</div>
</div>
&#13;
答案 3 :(得分:0)
您可以使用$(this)
对象来引用构成jQuery处理程序的元素:
$(document).ready(function(){
$('#table_1 .tableRow div').click(function(event) {
//Set the style for all divs
var myElements = document.querySelectorAll("#table_1 .tableRow div");
for (var i = 0; i < myElements.length; i++) {
myElements[i].className="blueText";
}
$(this).addClass('selectedText')
});
});
此外,如果您想使用CSS类以外的其他内容来确定是否选择了某个元素(在jQuery回调之外),您可以为其添加data-*
属性{{3} }。