如何简化这种重复的jquery?

时间:2009-10-18 10:59:46

标签: javascript jquery refactoring

此代码可让我在悬停/未覆盖相应的div时显示/隐藏自定义消息msg_one msg_two msg_three。将适当的消息注入#screen div,然后应用show / hide。除了前两行#one vs #two vs #three和显示的消息msg_one msg_two msg_three之外,代码几乎相同。

如何将其简化为更少的代码行以消除重复性?

var msg_one = "message 1";
var msg_two = "message 2";
var msg_three = "message 3";

$("#one").hover(function()  { 
    $("#screen").html(msg_one).show(); 
}, function(){ 
    $("#screen").html("").hide(); 
});

$("#two").hover(function()  { 
    $("#screen").html(msg_two).show(); 
}, function(){ 
    $("#screen").html("").hide(); 
});

$("#three").hover(function() { 
    $("#screen").html(msg_three).show(); 
}, function(){ 
    $("#screen").html("").hide(); 
});

感谢。

6 个答案:

答案 0 :(得分:5)

你可以像这样扩展jQuery:

$.fn.hover_message = function (message) {
    $(this).bind("hover", function()    { 
        $("#screen").html(message).show(); 
    }, function(){ 
        $("#screen").html("").hide(); 
    });
}

并使用这个功能:

$("#one").hover_message(msg_one);
$("#two").hover_message(msg_two);
$("#three").hover_message(msg_three);

答案 1 :(得分:3)

您可以将三条消息中的每条消息都放在相应title的{​​{1}}属性中。然后你可以在div中添加一个类,并且:

<div>

我希望代码有效,我把它写出来了:)。无论如何,这个想法还可以。

答案 2 :(得分:2)

var msgs = {
    'one': 'message 1',
    'two': 'message 2',
    'three': 'message 3'
}
$('#one, #two, #three').hover(function(){
    $("#screen").html(msgs[this.id]).show(); 
}, function () {
    $("#screen").html("").hide(); 
});

答案 3 :(得分:1)

如果“#one”,“#tw”和“#three”都在同一个容器中,你可以利用它:

$("#container").hover(function(e) {
    $("#screen").html($(e.target).attr("title")).show();
}, function(e) {
    $("#screen").html("").hide();
})

答案 4 :(得分:1)

[{elem: '#one', msg: msg_one },
 {elem: '#two', msg: msg_two },
 {elem: '#three', msg: msg_three }
].each(function(item) {
    $(item.elem).hover(function() {
        $("#screen").html(item.msg).show();
    },
    function() {
        $("#screen").html("").hide();
    });
});

答案 5 :(得分:1)

我会创建一个简单的插件,你可以长期重用:

<script type="text/javascript">
(function($){

    $.fn.hoverScreen = function(options){
        var config = $.extend({}, $.fn.hoverScreen.defaults, options);
        return this.each(function(){
            var $this = $(this);
            $this.hover(function(){
                config.screenElem.html(config.text).show();             
            }, function(){
                config.screenElem.html('').hide();
            });
        });
    }

    $.fn.hoverScreen.defaults = {
        screenElem: null,
        text: ''
    }

})(jQuery);
</script>

现在使用非常简单:     

$(function(){
    $.fn.hoverScreen.defaults.screenElem = $("#screen");
    $("#one").hoverScreen({ text: 'message one' });
    $("#two").hoverScreen({ text: 'message two' });
});       
相关问题