使用 .replacewith 更改图像,但保留 id.之后,图像不再在悬停时触发功能

Using .replacewith to change images but maintaining id. After that the image does not fire function on hover anymore

本文关键字:图像 悬停 功能 不再 id replacewith 使用 保留 之后      更新时间:2023-09-26

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

在这里我定义函数:

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关联的图像。

任何帮助表示赞赏!

因为您动态地将元素添加到 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"});
    });
})

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