如何使用悬停追加将数组项添加到TD?



当我将鼠标悬停在每个 td 上时,悬停功能起作用,但只将数组中的最后一项附加到所有 td,如何让它显示正确的汽车?

<!doctype html>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<table width="250px"  border="1" cellspacing="10" cellpadding="3">
<tr>
<td id ="id0">car 1</td>
</tr>
<tr>
<td id ="id1">car 2</td>
</tr>
<tr>
<td id ="id2">car 3</td>
</tr>
</table>
<script>
var cars = ["Saab", "Volvo", "BMW"];
for (i = 0; i < cars.length; i++) {
var car = cars[i]
$( "#id"+i ).hover(function() { 
$( this ).append( $( "<span> make is "+car+"</span>" ) );
}, 
function() {
$( this ).find( "span:last" ).remove();
}); 
} 
</script> 
</body>
</html>

问题解释:

在每个td上注册悬停事件的侦听器时,该函数会保留对car变量的引用。循环完成后,该变量将包含最新的数组值,因此当悬停事件的触发器启动时,它们将使用此最新值。

一个解决方案:

一种解决方案是将数组的idx保留在td元素上,就像一个额外的属性一样,然后你可以像下一个示例一样做:

var cars = ["Saab", "Volvo", "BMW"];
$(document).ready(function()
{
for (i = 0; i < cars.length; i++)
{
$( "#id" + i ).hover(function()
{
var car = cars[Number($(this).attr("cars-idx"))];
$(this).append($("<span> make is " + car + "</span>"));
}, 
function()
{
$(this).find("span:last").remove();
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<table width="250px"  border="1" cellspacing="10" cellpadding="3">
<tr>
<td id="id0" cars-idx="0">car 1</td>
</tr>
<tr>
<td id="id1" cars-idx="1">car 2</td>
</tr>
<tr>
<td id="id2" cars-idx="2">car 3</td>
</tr>
</table>

它将工作检查

<table width="250px"  border="1" cellspacing="10" cellpadding="3">
<tr>
<td id ="id0" data-id="0" class="carHover">car 1</td>
</tr>
<tr>
<td id ="id1"  data-id="1" class="carHover">car 2</td>
</tr>
<tr>
<td id ="id2"  data-id="2" class="carHover">car 3</td>
</tr>
</table>

Jquery

var cars = ["Saab", "Volvo", "BMW"];
$('.carHover').hover(function(){
var dynaicid= $(this).data('id');
$( this ).append( $( "<span> make is "+cars[dynaicid]+"</span>" ) );
});
$( ".carHover" ).mouseout(function() {
$( this ).find( "span" ).remove();
});

有多种方法可以做到这一点,基于 td 的 ID、数组的顺序等。

就个人而言,我会这样做:

var cars = ["Saab", "Volvo", "BMW"];
var i = 0;
// assign all of your values here, not ID based
$("table td").each(function(){
$(this).append("<span> make is "+cars[i]+"</span>" );
i++; 
});
// Hide all of them
$("table td span").hide();
// On hover, show the one you're hovering on, hide it again when you mouse 
off
$("table td").on({
mouseover: function() {
$(this).find("span").stop().show();
},
mouseout: function() {
$("table td span").stop().hide();
}
})