Javascript (jQuery)闪光效果:如何做到这一点

Javascript (jQuery) flasher effect: how to do that?

本文关键字:何做 这一点 jQuery Javascript      更新时间:2023-09-26

我想做一个闪光效果:当悬停在一些指定的字段有显示任何东西(黄色图标在我的情况下),当鼠标离开它消失。

的问题是,有很多这样的类似的领域(他们将在未来的评论),所以我已经尝试做所有这些在一个循环。但是没有用……我不知道为什么。

一些注意事项:我必须做到这一切没有html,只有在javascript中,所以我已经使用文档。写方法。

代码如下:

var data = ['one', 'two', 'three'];
for(var i in data){
    (function(){
        $('#id'+i).mouseover(function(){    $("#hdn"+i).show();   });
        $('#id'+i).mouseout(function(){    $("#hdn"+i).hide();   });
    });
    document.write('<div id="id'+i+'" style="border:1px solid;margin:10px 0;float:left;width:100%;">');
        document.write('<div style="float:left;width:20px;height:20px;">'+data[i]+'</div>');
        document.write('<div id="hdn'+i+'" style="display:none;float:right;width:20px;height:20px;"><img src="http://t0.gstatic.com/images?q=tbn:ANd9GcSa7ebCG4VGWcTTXH8j7ebfpFWhYuV9ojisNmsrnZaQHk8wRMTNqGfaNA" /></div>')
    document.write('</div>');
}

谢谢!

var data = ['one', 'two', 'three'];
$.each(data,function(i,v) {
    $('<div id="id'+i+'" style="border:1px solid;margin:10px 0;float:left;width:100%;">')
        .append('<div style="float:left;width:20px;height:20px;">'
                 +v+'</div><div id="hdn'
                 +i+'" style="display:none;float:right;width:20px;height:20px;"><img src="http://t0.gstatic.com/images?q=tbn:ANd9GcSa7ebCG4VGWcTTXH8j7ebfpFWhYuV9ojisNmsrnZaQHk8wRMTNqGfaNA" /></div>')
        .appendTo('body')
        .mouseover(function(){    $(this).children('[id^="hdn"]').show();   })
        .mouseout(function(){    $(this).children('[id^="hdn"]').hide();   });
});

在写出html之前设置了事件处理程序。这不行。

另外,JavaScript中的for in循环会给你数组的索引,而不是实际值。

最好的方法是为html设置一个div,将这个html添加到它,然后让jQuery将div添加到你的body。

var newHtml = "";
for(var i = 0; i < data.length; i++) {
    newHtml += '<div id="id'+i+'" style="border:1px solid;margin:10px 0;float:left;width:100%;">';
        newHtml += '<div style="float:left;width:20px;height:20px;">'+data[i]+'</div>';
        newHtml += '<div id="hdn'+i+'" style="display:none;float:right;width:20px;height:20px;"><img src="http://t0.gstatic.com/images?q=tbn:ANd9GcSa7ebCG4VGWcTTXH8j7ebfpFWhYuV9ojisNmsrnZaQHk8wRMTNqGfaNA" /></div>';
    newHtml += '</div>';
}
var newDiv = $("<div />");
$("body").append(newDiv);
$(newDiv).html(newHtml);
for(var i = 0; i < data.length; i++) {
    (function(){
        $('#id'+i).mouseover(function(){    $("#hdn"+i).show();   });
        $('#id'+i).mouseout(function(){    $("#hdn"+i).hide();   });
    });

如果您使用类名而不是id,您可以一次影响多个元素。另外,不要使用document.write,而是更新现有元素的innerHTML。

$('#outputDIV').html("....")