[英]How to set the highlight of a table row with jquery from a javascript function call from an onclick in the table row?
我想在用户正在与之交互的表格行中添加一个漂亮的浅黄色突出显示。 他们点击一个带有'onclick'函数调用的'A'链接,该调用使用jquery来做东西(不重要)。 onclick位于“A”标签和表格单元“TD”中。
这是表格单元格:
<td>
<a href="javascript:void(0);"
onclick="deleteSchedule('Ajax/Admin_Delete_Schedule.cfm?SID=12345');"
title="Delete User"><img src="images/Delete_x16_.png" border="0"></a>
</td>
如何获取表格行的参考,然后设置背景颜色? 我是否需要为每个表行提供唯一的ID?
由于答案非常详细和优秀,我将补充一点:我想在我的功能中这样做,但我不知道如何用'this'来做到这一点。 谢谢!! 和OMG! stackoverflow是最棒的!
我无法得到以下最接近或父母的例子,但我确实让这个工作:
$(".rowClick").on("click", function() {
$(this).closest("tr").css('backgroundColor', '#FFFF99');
});
当然我把'rowClick'这个类加到了'A'标签上。 现在的问题是,当用户点击另一行时,结果是两行突出显示。 有关从先前选定的行中删除突出显示的任何建议。 (我猜测要更改所有表格行的背景颜色,然后设置点击的那一行。) - 再次感谢!
首先,不要使用内联onclick方法。 设置适当的jQuery事件委托功能。 所以做这样的事情:
$(function(){
$('td a').click(function(e){
// 'e' refers to the event target here
var row = $(e.target).closest('tr');
// Insert whatever color value where yellow is
$(row).css('backgroundColor', 'yellow')
})
})
更好的是创建一个类似的CSS类
.tr-highlighted { background: yellow; transition: 200ms linear; }
然后使用类切换功能添加/删除该类
$(function(){
$('td a').click(function(e){
// 'e' refers to the event target here
var row = $(e.target).parent();
// Insert whatever color value where yellow is
$(row).toggleClass('tr-highlighted')
})
})
如果你必须使用一个内嵌onclick
声明,上面应该仍然适用,但是你需要访问this
在函数中引用事件目标,而不是e
被作为参数传递。
或者,如果您只想在人物悬停在表格行上时突出显示它,则可以完全不使用JS
tr:hover { background: yellow; transition: 200ms linear; }
为此,您可以使用jQuery .closest()函数。
$("td").click(function(e){
$(e.target).closest("tr").css("background-color","yellow");
$(e.target).closest("tr").siblings().css("background-color","white");
});
这个简单的英文代码如下:
For each table cell that is clicked:
Find the nearest row and change its background color to yellow.
Find all of the other rows in the table and change their background colors to white.
http://jsfiddle.net/ogzankse/2/
编辑:我更改了代码以更好地反映您的情况。 我没有将click事件监听器附加到行本身,而是在每行中添加了锚标记,并将监听器附加到该行。 我在锚标记中添加了一个类,以便忽略表外的锚点。 代码现在搜索被点击的<a>
标签所在的<td>
,然后找到最近的行并应用CSS。 代码现在是:
$("a.intable").click(function(e){
$(e.target).parent().closest("tr").css("background-color","yellow");
$(e.target).parent().closest("tr").siblings().css("background-color","white");
});
我建议给锚点一个类名,即“rowClick”,并使用JavaScript将类切换到TR。
<tr>
<td>
...
<a class="rowClick">
...
</td>
</tr>
CSS定义:
.bgYellow{ background-color: #FFFF00; }
这是一个使用jQuery的例子:
$(".rowClick").on("click", function() {
$(this).closest("tr").addClass("bgYellow");
});
根据您正在执行的操作,您可以将函数修改为toggleClass或其他misc。 选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.