有沒有辦法在jQuery中通過名稱調用方法?例如:jQuery:從字符串執行方法
var condition = true;
$('div').execute(condition ? 'show':'hide');
有沒有辦法在jQuery中通過名稱調用方法?例如:jQuery:從字符串執行方法
var condition = true;
$('div').execute(condition ? 'show':'hide');
是,使用[]
標記訪問(使用.
,而不是字面的)jQuery對象的屬性:
$('div')[condition ? 'show' : 'hide']();
你也可以這樣做:
$('div').toggle(condition);
http://www.jibbering.com/faq/faq_notes/square_brackets.html
編輯:萬一你喜歡你自己的編碼風格,你可以補充一點:
$.fn.execute = function(a) {
return this[a].apply(this, [].slice.call(arguments, 1));
}
然後,你可以這樣做:
$('div').execute(condition ? 'show' : 'hide');
或
$('div').execute(condition ? 'keydown' : 'keyup', function() {...});
Javascript對象基本上是字典。
var condition = true;
$('div')[condition ? 'show':'hide']();
或者只是使用切換:-) – Alex
你在做什麼?可能有更好的解決方案_not_不涉及基於字典的訪問方法。 – Spycho