0

当用户将鼠标悬停在带有包含复选框"id=dot0001"的表格的图像上时,该表格变为可见。当用户选中该框时,图像将替换为具有相同 ID 的图像。该部分工作正常,用户可以根据需要检查和取消选中,图像被正确替换。问题:当用户离开图像后再次将鼠标悬停在图像上时,表格不会出现。id= "info0001"id="checkbox0001"id="dot0001"

这里我定义了函数:

function makevisible(a){ 
    $("#tablespace").after(
        '<table  border="4" id="info'+a+'"class="info'+a+'">'+
        '<tr><td>Add to favorits</td><td><input name="" type="checkbox" id="checkboxinfo'+a+'" value=""></td></tr>')

        $("#info"+a).css("visibility", "hidden")

        $('#checkboxinfo'+a).change(function() {

        if($('#checkboxinfo'+a).is(':checked')){
    $('#dot'+a).replaceWith('<img src="_index/_dots/dotfavorit.gif" id="dot'+a+'" class="dot'+a+'">')
        }
else{
    $('#dot'+a).replaceWith('<img src="_index/_dots/dotnormal.gif" id="dot'+a+'" class="dot'+a+'">')  
    }   
    })

};

这里我使用函数:

$(document).ready(function() {
    $("#dot0002").hover(makevisible("0002"))
    })

这使得表格在添加到 html 后可见和隐藏:

    $(document).ready(function() {

$("#dot0002").hover(
  function(){
    $("#info0002").css({"visibility":"visible"});
  },
  function(){
    $("#info0002").css({"visibility":"hidden"});
  }
);

$("#info0002").hover(
  function(){
    $(this).css({"visibility":"visible"});
  },
  function(){
    $(this).css({"visibility":"hidden"});
  }
);
});

这是一个小提琴:http: //jsfiddle.net/QzX9C/

我认为问题是 jQuery 在替换后找不到与 id 关联的图像。

任何帮助表示赞赏!

4

1 回答 1

1

因为您将元素动态添加到 DOM,所以该Hover函数不会附加到您的新元素:

这:

$("#dot0002").hover(
function () {
    $("#info0002").css({"visibility": "visible"});
},
function () {
    $("#info0002").css({"visibility": "hidden"});
});

不会附加到图像上,因为它是通过这行代码动态注入到 DOM 中的:

$('#dot'+a).replaceWith('<img src="_index/_dots/dotfavorit.gif" id="dot'+a+'" class="dot'+a+'">')

除非您通过向 .change() 函数添加悬停触发器来重新附加它

$('#checkboxinfo' + a).change(function () {
    if ($('#checkboxinfo' + a).is(':checked')) {
        $('#dot' + a).replaceWith('<img src="_index/_dots/dotfavorit.gif" id="dot' + a + '" class="dot' + a + '">')
    } 
    else {
        $('#dot' + a).replaceWith('<img src="_index/_dots/dotnormal.gif" id="dot' + a + '" class="dot' + a + '">')
    }

    //Add this code at the end to reattach the hover event on the newlly injected image
    $('#dot' + a).hover(
    function () {
        $("#info" + a).css({"visibility": "visible"});
    },
    function () {
        $("#info" + a).css({"visibility": "hidden"});
    });
})

这是您的小提琴更新:链接...

于 2013-01-29T04:09:09.710 回答