使用循环优化Jquery

Fra*_*ank 4 jquery loops

我有这个代码:

            $('.counter_d').mouseover(function() {
                   $('#description').html('Counter');
             });
            $('.selector_d').mouseover(function() {
                   $('#description').html('Selector');
             });
             $('.date_d').mouseover(function() {
                   $('#description').html('Date');
             });
Run Code Online (Sandbox Code Playgroud)

还有几个,但我认为文件可以更小,甚至可以使用循环重用,但我无法将描述(HTML方法)与选择器绑定.

我想用这样的东西:

              var selectors=['.counter_d','.selector_d','.date_d'];
              var description=['Counter', 'Selector', 'Date'];


              for(var i=0; i<selectors.length; i++)
                 $(selectors[i]).mouseover(function() {
                   $('#description').html(description[i]);
                 });
Run Code Online (Sandbox Code Playgroud)

有帮助吗?谢谢

And*_*ker 8

var selectors = {
    '.counter_d': 'Counter',
    '.selector_d': 'Selector',
    '.date_d': 'Date'
};


$.each(selectors, function (key, value) {
    $(key).mouseover(function () {
        $("#description").html(value);
    });
});
Run Code Online (Sandbox Code Playgroud)

示例: http ://jsfiddle.net/andrewwhitaker/bS28q/

  • 我想发布非常相似的答案,给出这个代码作为一个例子:http://jsfiddle.net/vxd9n/,但你更快.但是,你可以在事件处理程序之外提取`$('#description')`,因为每次触发事件处理程序时都不需要执行它.如果你将它放在`$ .each()`的回调中,它将被执行`selectors`的每个元素.因此,将它放在定义"选择器"的位置会更好.无论如何,值得upvoting.+1 (3认同)