命名空间全局变量问题

| 我对名称空间和全局变量非常陌生。我目前有此代码:
$(\'#formats1\').hover(function() {
    var tag = \'div.cds\';
    var offset = $(this).position();
    var width = $(tag).outerWidth();
    var height = $(tag).outerHeight();
    $(tag).show();
    $(tag).css(\'left\', offset.left - width + \'px\');
    $(tag).css(\'top\', offset.top - height + \'px\');
}, function() {
    $(\"div.cds\").hide();
});

$(\'#formats2\').hover(function() {
    var tag = \'div.lp\';
    var offset = $(this).position();
    var width = $(tag).outerWidth();
    var height = $(tag).outerHeight();
    $(tag).show();
    $(tag).css(\'left\', offset.left - width + \'px\');
    $(tag).css(\'top\', offset.top - height + \'px\');
}, function() {
    $(\"div.lp\").hide();
});
目前,各个div重复了很多次。 我觉得这是合并名称空间和全局变量的好机会,但是我不确定该怎么做。有任何想法吗? 谢谢!     
已邀请:
为什么不尝试使用功能?
$(\'#formats1\').hover(function() {
    do_hover(\'div.cds\', this);
}, function() {
    $(\"div.cds\").hide();
});

$(\'#formats1\').hover(function() {
    do_hover(\'div.lp\', this);
}, function() {
    $(\"div.lp\").hide();
});

function do_hover(tag, self){
    var offset = $(self).position();
    var width = $(tag).outerWidth();
    var height = $(tag).outerHeight();
    $(tag).show();
    $(tag).css(\'left\', offset.left - width + \'px\');
    $(tag).css(\'top\', offset.top - height + \'px\');
}
    
好吧,创建名称空间并不惜一切代价避免使用全局变量始终是一个非常好的主意。但是在这种情况下,您只需要一点Javascript和jQuery糖:
var data = [{id: \'#formats1\', tag: \'div.cds\'}, {id: \'#formats2\', tag: \'div.lp\'} /*, ... */];

$.each(data, function( _, info ) {
    $(info.id).hover(function() {
        var $tag = $(info.tag),
            mypos = $.extend({
                width: $tag.outerWidth(),
                height: $tag.outerHeight()
            }, $(this).position());

        $tag.show().css({
            left: mypos.left - mypos.width + \'px\',
            top: mypos.top - mypos.height + \'px\'
        });
    }, function() { 
       $(\"div.cds\").hide();
    });
});
此处应闭合的唯一合理变量是
$(\'div.cds\')
。例如,您可以将整个代码包装成一个自调用方法:
(function _namespace() {
    var $tag = $(\'#div.cds\');

    $(\'#formats1, #formats2\').hover(function() {
    });
    // ...
}());
    
您可以将要使用的类附加到悬停的项目。因此,如果您的HTML看起来像这样:
<div id=\"formats1\" data-tagclass=\"cds\">...</div>
<div id=\"formats2\" data-tagclass=\"lps\">...</div>
然后,您可以在JavaScript中这样做:
$(\'#formats1, formats2\').hover(function() {
    var $this  = $(this);
    var $tag   = $(\'div.\' + $this.data(\'tagclass\'));
    var offset = $this.position();
    var width  = $tag.outerWidth();
    var height = $tag.outerHeight();
    $tag.show();
    $tag.css(\'left\', offset.left - width  + \'px\');
    $tag.css(\'top\',  offset.top  - height + \'px\');
}, function() {
    $(\'div.\' + $this.data(\'tagclass\')).hide();
});
如果您使用的是旧版jQuery,则可能需要使用
$this.attr(\'data-tagclass\')
而不是
$this.data(\'tagclass\')
。     

要回复问题请先登录注册