[英]Select the first html table row on page load using JS or JQUERY
[英]How to highlight first row of table JQuery on page load ?
如果單擊任何行,我的以下代碼將正常工作:
$(document).ready(function() {
$('#currentloc_table tr').click(function(event) {
$("#"+$(this).attr('id')+" input:checkbox")[0].checked = ! ($("#"+$(this).attr('id')+" input:checkbox")[0].checked);
if($("#"+$(this).attr('id')+" input:checkbox")[0].checked == true)
$(this).addClass('selected');
else if($("#"+$(this).attr('id')+" input:checkbox")[0].checked == false)
$(this).removeClass('selected');
});
});
這是CSS:
.selected td {
background: yellow;
}
我需要頁面加載時,此表的第一行應突出顯示。 我怎樣才能做到這一點?
嘗試這個
$(document).ready(function () {
$('#currentloc_table tr').click(function (event) {
$("#" + $(this).attr('id') + " input:checkbox")[0].checked = !($("#" + $(this).attr('id') + " input:checkbox")[0].checked);
if ($("#" + $(this).attr('id') + " input:checkbox")[0].checked == true)
$(this).addClass('selected');
else if ($("#" + $(this).attr('id') + " input:checkbox")[0].checked == false)
$(this).removeClass('selected');
});
// Add these lines
var firstTr = $('#currentloc_table tr:first');
firstTr.addClass('selected');
firstTr.find("input:checkbox")[0].checked = true;
});
工作演示
您可以嘗試使用.first()
或:first()
來選擇目標:
$(document).ready(function() {
$('#currentloc_table tr').first().addClass('selected');
....
要么:
$(document).ready(function() {
$('#currentloc_table tr:first').addClass('selected');
....
您可以查看以下內容:
.eq()
和:eq()
nth-child()
:first-child
加載后觸發功能
$('#currentloc_table tr:first-child').trigger('click');
為此,您應在將click事件綁定到以下項后添加:
#currentloc_table tr
試試這個
$(document).ready(function(){
$("#currentloc_table tr:first"):css('background','yellow');
})
否則嘗試
$("#currentloc_table tr").eq(0):css('background','yellow');
似乎您的代碼可以得到明顯改進:
$('#currentloc_table tr').click(function (event) {
var check = $("input:checkbox", this)[0];
check.checked = !check.checked;
$(this)[check.checked ? 'addClass' : 'removeClass']('selected');
});
要選擇第一行:
$('#currentloc_table tr:first').click();
$(document).ready(function () {
$('#currentloc_table').find('tr:first').addClass('selected');
});
嘗試這個 ,
$(document).ready(function() {
$('#currentloc_table tr').first().addClass('selected_f');
// rest of your stuff ....
和CSS
.selected_f {
background: yellow;
}
您的CSS類作為所選類的默認類,因此不會添加該類,因此無法看到效果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.