【发布时间】:2017-02-23 03:30:06
【问题描述】:
我需要在 altKey 按下和鼠标悬停时更改背景和文本颜色。
问题是,我只能对 HTML 代码中显示的第一行执行此操作,而不能在之后使用 jQuery 附加的行中执行此操作。
HTML 代码:
<div class = "table1">
<table id = "t1" align="center" border=1>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>Telephone Number</th>
</tr>
<tr id = "r">
<tbody>
<td id = "d1" class = "el" contenteditable="true"></td>
<td id = "d2" class = "el" contenteditable="true"></td>
<td id = "d3" class = "el" contenteditable="true"></td>
<td id = "d4" class = "el" contenteditable="true"></td>
<td><button id="del1">Delete</button></td>
</tbody>
</tr>
</table>
</div>
jQuery 代码:
$(document).ready(function(){
$("#b1").click(function(){
$('#t1 > tbody:last-child').append('<tr id = "r"><td id = "d1" class = "el" contenteditable="true"></td><td id = "d2" class = "el" contenteditable="true"></td><td id = "d3" class = "el" contenteditable="true"></td><td id = "d4" class = "el" contenteditable="true"></td><td><button id ="del1">Delete</button></td></tr>');
});
$("#t1").on('click','#del1',function(){
$(this).parent().parent().remove();
});
function handler(ev) {
var target = $(ev.target);
var elId = target.attr('id');
if( target.is(".el") ) {
$(this).css("background-color","white");
$(this).css("color","black");
}
}
$(".el").mouseleave(handler);
$(".el").bind('mouseenter keypress','.el', function(e) {
if (e.altKey) {
$(this).css("background-color","blue");
$(this).css("color","red");
}
});
})
【问题讨论】:
-
您正在使用相同的 id 附加所有行。 id 必须是唯一的。解决这个问题,你的 CSS 就可以工作了。
标签: javascript jquery html css dynamic