jQuery为什么动态添加的图像在悬停时不会显示/隐藏

jQuery Why dynamically added images are not getting shown/hidded on hover

本文关键字:显示 隐藏 悬停 动态 为什么 添加 图像 jQuery      更新时间:2023-09-26

当我将鼠标悬停在中封装的标题上时,我正试图编写一个显示链接图标的代码

我所做的是,我有一个CSS类samplea。与CCD_ 3有多个CCD_。然后我插入jQuery,在<a>之后添加自定义链接图像。我一开始把照片藏了起来。然后添加了jQuery,这样当它悬停在标题上时就会显示/隐藏。

然而,我能够在所有<a class='samplea'>之后插入图像,但不能隐藏/显示它们。

HTML

<h3><a class="samplea"  id="aid">Sample Title</a></h3>
<h3><a class="samplea"  id="a1">Sample Title</a></h3>
<h3><a class="samplea"  id="a1">Sample Title</a></h3>

CSS

.samplea {  
    }

JS

 $(document).ready(function () {
        var permalinkid = 1;
        $(".samplea").each(function (index) {
            $(this).after("&nbsp;&nbsp;<img src='http://www.spotzerblog.com/wp-content/themes/StandardTheme_261/images/icn_permalink.png' id='permalink" + permalinkid + "' />");
            //if you comment below line it will show the link icons 
            //appropriately
            $("#permalink" + permalinkid).hide();                
            $(this).hover(
                   function () { $("#permalink" + permalinkid).show(); },
                   function () { $("#permalink" + permalinkid).hide(); }
            );
            permalinkid = permalinkid + 1;               
        });
    });

为什么会这样?这是相应的JSFiddle。

试试这个:

// New way (jQuery 1.7+) - .on(events, selector, handler)
$(document).on('mouseenter mouseleave', 'h3', function () {
    $(this).find('img').toggle();
});

FIDDLE演示

您在每次迭代中都在递增permalinkid = permalinkid + 1,但只有当您进行"悬停"时才会对其求值,这将使其成为permalink4http://jsfiddle.net/balintbako/G3Psm/5/Palash Mondal的答案是从本质上解决你的问题,然而,如果你想保持它的ID基础,那么请检查:http://jsfiddle.net/balintbako/G3Psm/9/

$(document).ready(function () {
    var permalinkid = 1;
    $(".samplea").each(function (index) {
        var temp = permalinkid;
        $(this).after($("<div id='permalink" + temp + "'>text</div>"));
        //if you comment below line it will show link icon
        //appropriately        
        $("#permalink" + permalinkid).hide();
        $(this).hover(
        function () {
            $("#permalink" + temp).show();
        },
        function () {
            $("#permalink" + temp).hide();
        });
        permalinkid = permalinkid + 1;
    });
});