单击按钮时突出显示行

Highlight row when clicked on button

本文关键字:显示 按钮 单击      更新时间:2023-09-26

当我单击该行的编辑按钮时,我使用以下脚本突出显示该行。当我点击按钮时,我正在传递行的 ID!我的问题是代码在Mozila Firefox中有效,但在Google Chrome上不起作用。以下代码有什么问题。

function high(id)
{
    $('tr').removeAttr('style'); 
    document.getElementById(id).style="background-color:#eeeeea;color:#000000;font-weight:500;";
}

试试这个,

$('#'+id).attr("style","background-color:#eeeeea;color:#000000;font-weight:500;");

也在铬上工作。

原因,可以是样式是一个对象,其中包含一些属性 Chrome 可能不允许覆盖它。所以自定义字符串你 传入样式将不适用于它,因此不会对 元素。

您需要单独设置样式对象的属性。

var elem = document.getElementById(id);
//Set properties
elem.style.color = "#000000";
elem.style.fontWeight = "500";
elem.style.backgroundColor = "#eeeeea";

既然你使用的是jquery,你可以使用.css()

$('#' + id).css({
    "background-color" :"#eeeeea",
    "color":"#000000",
    "font-weight":"500";
});

但是,我建议您创建一个CSS类然后使用它。

$('tr').removeClass('highlight'); 
$('#' + id).addClass('highlight');

这是一个演示,用于向编辑行添加特殊类并删除其他行上的类。这是使用 jquery 的 closest() 方法完成的。您甚至不需要为此使用任何 id。

$("button").on("click",function(){
		$("tr").each(function(){
			$(this).removeClass("marked");
		});
		$(this).closest("tr").addClass("marked");
	});
	.marked{
		background-color:#eeeeea;color:#000000;font-weight:500;
	}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
	<table>
		<tr>
			<td>This is TD</td>
			<td><button>Edit</button></td>
		</tr>
		<tr>
			<td>This is TD</td>
			<td><button>Edit</button></td>
		</tr>
		<tr>
			<td>This is TD</td>
			<td><button>Edit</button></td>
		</tr>
	</table>