假设我在PHP循环中有一个这样的表,其中包含<tr>
和<td>
:
//Some code...
echo "<table id='rowClick'>";
while($row=mysql_fetch_assoc($result){
echo "<tr><td><input type='text' value='{$row['item']}'></td></tr>";
}
echo "</table>";
//Rest of code
我使用了CSS:
table tr.active{
background:red;
}
对于JQuery:
<script>
$(document).ready(function(){
$("#rowClick").children("tbody").children("tr").children("td").keydown(function(){
$(this.parentNode).toggleClass("active");
});
$("#rowClick").children("tbody").children("tr").children("td").keyup(function(){
$(this.parentNode).toggleClass("active");
});
});
</script>
我对JQuery不太熟悉。我所希望的是,当用户在任何一行中选择<td>
输入字段(或被聚焦)时,<tr>
的颜色将发生变化。根据上面的jquery,它可以工作,但并不像预期的那样,因为每次我选择输入字段时,它都会变成红色,然后在选择下一个字段时,会返回到默认的表格颜色,依此类推。
我想这就是您想要的:
$(document).ready(function(){
$("#rowClick").find("input").on("focus", function(){
$(this).closest("tr").addClass("active");
}).on("blur", function() {
$(this).closest("tr").removeClass("active");
})
});
我将目标对准表中的input
以寻找焦点/模糊,然后根据输入,我将目标瞄准最接近的父tr
以高亮显示。
JSFiddle
如果你想突出显示td
,只需将其作为目标:
JSFiddle
你说什么时候聚焦,但我不明白你为什么用keydown/keyup?它们用于键盘事件。阅读此处
尝试:
$("#rowClick tr input").on("focus", function(){
$("#rowClick tr").removeClass("active");
$(this).parents("tr").addClass("active")
})
您在tr上分配了点击事件,该事件不在td上,但它会冒泡到tr上,因为您正在更改整行的颜色,所以它更干净。
您可以使用文本框的焦点和焦点输出事件来针对其父<tr>
,并根据需要添加和删除活动类:
$(function() {
$('#rowClick input').on('focus', function() {
$(this).closest('tr').addClass('active');
}).on('focusout', function() {
$(this).closest('tr').removeClass('active');
});
});
由于focusin/focusout事件是冒泡的(与blur不同),您可以通过将侦听器实际附加到tr而不是输入来简化事情。这样做的好处是,如果您在同一行中的输入之间进行更改,它不会触发(因为不需要它……您仍然在同一列中)。像这样:
$(document).ready(function(){
$("#rowClick tr").focusin(function(){
$(this).addClass("active");
}).focusout(function() {
$(this).removeClass("active");
});
});
table tr.active{
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='rowClick'>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
</table>