2011-05-21 16 views
1
$('#elmLeft').button({ 
      icons: { 
       primary: "ui-icon-triangle-1-w" 
      }, 
      text: false 
     }); 
$('#elmRight').button({ 
      icons: { 
       primary: "ui-icon-triangle-1-e" 
      }, 
      text: false 
     }); 
$('#elmTop').button({ 
      icons: { 
       primary: "ui-icon-triangle-1-n" 
      }, 
      text: false 
     }); 
$('#elmBottom').button({ 
      icons: { 
       primary: "ui-icon-triangle-1-s" 
      }, 
      text: false 
     }); 

回答

4
function setButton($element, icon) { 
    $element.button({ 
      icons: { 
       primary: icon 
      }, 
      text: false 
     }); 
} 
setButton($('#elmLeft'), "ui-icon-triangle-1-w"); 
setButton($('#elmRight'), "ui-icon-triangle-1-e"); 
setButton($('#elmTop'), "ui-icon-triangle-1-n"); 
setButton($('#elmBottom'), "ui-icon-triangle-1-s"); 

另外,您可以只取選擇,而不是一個jQuery元素,只有字符串的最後一個字母,但似乎有點小題大做。

0

我敢肯定,它可以縮短,但不是以一種優雅的方式,據我所知,簡潔將以可理解性爲代價。

1

你可以把一個對象的圖標不同,並用它來改變primary

var icons = { 
    elmLeft: 'w', 
    elmRight: 'e', 
    elmTop: 'n', 
    elmBottom: 's' 
}; 
$('#elmLeft, #elmRight, #elmTop, #elmBottom').each(function() { 
    $(this).button({ 
     icons: { primary: 'ui-icon-triangle-1-' + icons[this.id] }, 
     text: false 
    }); 
}); 

我不知道你是否會考慮足夠乾燥,雖然保證了額外的複雜性。如果你有上的按鈕一類,那麼你可以把它用清潔劑:

$('.some_class').each(function() { 
    // As above. 
}); 

或者你可以將函數添加到icons保持id和圖標信息一起:

var icons = { 
    elmLeft: 'w', 
    elmRight: 'e', 
    elmTop: 'n', 
    elmBottom: 's', 
    button: function(id) { 
     $('#' + id').button({ 
      icons: { primary: 'ui-icon-triangle-1-' + this[id] }, 
      text: false 
     }); 
    } 
}; 
icons.button('elmLeft'); 
icons.button('elmRight'); 
icons.button('elmTop'); 
icons.button('elmBottom'); 

還是拿這一步:

var buttons = { 
    ids: { 
     elmLeft: 'w', 
     elmRight: 'e', 
     elmTop: 'n', 
     elmBottom: 's' 
    }, 
    create: function() { 
     for(id in this.ids) { 
      if(this.ids.hasOwnProperty(id)) { 
       $('#' + id').button({ 
        icons: { primary: 'ui-icon-triangle-1-' + this.ids[id] }, 
        text: false 
       }); 
      } 
     } 
    } 
}; 
buttons.create(); 

你可以做上面有一個自動執行的功能,如果你想要一個更清潔的命名空間:

(function() { 
    var ids = { 
     elmLeft: 'w', 
     elmRight: 'e', 
     elmTop: 'n', 
     elmBottom: 's' 
    }; 
    for(id in ids) { 
     if(ids.hasOwnProperty(id)) { 
      $('#' + id').button({ 
       icons: { primary: 'ui-icon-triangle-1-' + ids[id] }, 
       text: false 
      }); 
     } 
    } 
})(); 
+0

謝謝+1。但我認爲戴維的答案更實際。 – Pinkie 2011-05-21 21:43:59

+0

+ 1/-1爲過度工程(所以淨0,很酷,但留下代碼的讀者認爲跆拳道應該這樣做?) – Davy8 2011-05-21 22:29:34

+0

@ Davy8:在實踐中,我會用Pinkie的原始和重新格式化它使查找差異更容易(並可能添加評論指出差異在哪裏)。但有時我覺得好玩。 – 2011-05-22 00:41:28