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

时间:2018-10-24 15:09:52

标签: jquery hover append

当我将鼠标悬停在每个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>

3 个答案:

答案 0 :(得分:0)

它将可以检查

<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();
});

答案 1 :(得分:0)

问题说明:

当您在每个 td 上为 hover 事件注册侦听器时,该函数将保留对 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>

答案 2 :(得分:0)

基于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();
    }
})