簡體   English   中英

如何簡化這種重復的jquery?

[英]How can I simplify this repetitive jquery?

當代碼懸停/未覆蓋時,此代碼允許我顯示/隱藏自定義消息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(); 
});

謝謝。

您可以擴展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);

您可以將三條消息中的每條消息放在相應<div>title屬性中。 然后你可以添加一個類到divs:

$('.hover-div').hover(function()  { 
    var msg = $(this).attr('title');
    $("#screen").html(msg).show(); 
}, function(){ 
    $("#screen").html("").hide(); 
});

我希望代碼有效,我把它寫出來了:)。 無論如何,這個想法還可以。

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(); 
});

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

$("#container").hover(function(e) {
    $("#screen").html($(e.target).attr("title")).show();
}, function(e) {
    $("#screen").html("").hide();
})
[{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();
    });
});

我會創建一個簡單的插件,你可以長期重用:

<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' });
});       

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM