2014-02-18 54 views
0

我製作了以下代碼來轉換所有必須應用jquery.ui樣式的所有a元素,input type="submit元素,button元素和accordion div。迭代DOM元素並應用jquery-ui

我已經使用道具(「類型」)和標記名找出我循環什麼控制:

$(function() { 
    $('body *:not(script, style, noscript)').each(function() { 
     var t = $(this).prop('type'); 
     if (t != undefined && t !="") { 
      if (t.indexOf("select") != "-1") { 
       $(this).combobox(); 
      } 
      else if (t.indexOf("button") != "-1") { 
       $(this).button(); 
      } 
     } 

     if ($(this).get(0).tagName == "DIV" && 
      $(this).get(0).id != undefined && 
      $(this).get(0).id.toUpperCase() == "ACCORDION") { 

      $(this).accordion({ collapsible: true }); 

     } else if ($(this).get(0).tagName == "A" || 
        ($(this).get(0).tagName == "INPUT" && 
        $(this).prop('type') == "submit")) { 
      $(this).button(); 
     } 
    }); 
}); 

顯然,這是工作真棒。這個jquery就緒函數包含在我的asp.net mvc佈局頁面中,當我添加一個新的控件時,它是jQuery-ui呈現的。

但問題是。你有沒有做過這樣的事情?有更好的方法嗎?

回答

1

您可以使用jQuery簡化一點你的代碼的優勢:

$(function() { 

    // Use selectors to get DOM elements you are interested in 
    $('a, input[type=submit], button, select, .accordion').each(function() { 

     // Create the jQuery object only once, avoid doing $(this) each time 
     var $el = $(this); 

     if($el.is('a') || $el.is('input[type=submit]') || $el.is('button')) 
      $el.button(); 
     else if($el.is('.accordion')) 
      $el.accordion({ collapsible: true }); 
     else if($el.is('select')) 
      $el.combobox(); 
    }); 
}); 

更簡單的/可讀的方式可能是這樣的:

$(function() { 
    $('a, input[type=submit], button').button(); 
    $('.accordion').accordion({ collapsible: true }); 
    $('select').combobox(); 
}); 

看到它在行動在此jsFiddle

注1:如果div的ID爲accordion,並且css類別爲accordion(選擇器.accordion),我替換了您的測試檢查。元素ID在DOM樹中必須是唯一的,因此如果您有多個ID爲accordion的div,請將其替換爲css類accordion

注2:的jQuery UI沒有組合框控件的開箱(據我所知),也許你正在使用http://jqueryui.com/autocomplete/#combobox

+0

呀進出口使用自動完成 –

+0

大答案的方式;) –

+0

謝謝,很高興,如果它幫助你;) – rd3n