Highlight row when clicked on button

时光毁灭记忆、已成空白 提交于 2020-01-05 13:06:30

问题


I am using following script to highlight row when I clicked edit button of that row. I am passing Id of row when I click on button! My problem is the code is working in Mozila Firefox but not on Google Chrome. What is wrong in following code.

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

回答1:


Try this,

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

Working on chrome also.

The reason, can be style is an object which has some properties in it and chrome may not allow to overwrite it. So the custom string you passed in style will not apply to it, hence no changes applied to the element.




回答2:


Here is a demo to add special class to the editing row and remove the class on the other rows. This is done using the closest() method of jquery. You even do not need to use any id for this.

$("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>



回答3:


You need to set properties of style object individually.

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

Since you are using jquery, You can use .css()

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

However, I would recommend you to create a CSS class then use it.

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


来源:https://stackoverflow.com/questions/29075805/highlight-row-when-clicked-on-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!