2015-02-24 49 views
-3

我有一個腳本,用於檢查在下拉列表中選擇某些選項的次數。該頁面有大約一千個或更多的下拉菜單。選擇下拉菜單後,單擊所需的選項後,我們會在選擇並更新值之前約5秒鐘凍結。當刪除JavaScript時,它立即運行並確定。有沒有加快JavaScript運行速度的方法?加速JavaScript

這是下面的腳本:

<script type="text/javascript"> 

    function getSelectedValues(){ 
     var matches1 = $('#group1 select').filter(function(){ 
      return $(this).val() == '1'; 
     }).length; 
     var matches2 = $('#group2 select').filter(function(){ 
      return $(this).val() == '2'; 
     }).length; 
     var matches3 = $('#group3 select').filter(function(){ 
      return $(this).val() == '3'; 
     }).length; 
      var matches4 = $('#group4 select').filter(function(){ 
      return $(this).val() == '4'; 
     }).length; 
      var matches5 = $('#group5 select').filter(function(){ 
      return $(this).val() == '5'; 
     }).length; 
      var matches6 = $('#group6 select').filter(function(){ 
      return $(this).val() == '6'; 
     }).length; 
      var matches7 = $('#group7 select').filter(function(){ 
      return $(this).val() == '7'; 
     }).length; 

     // here's where we just update that new <span> 
     if(matches1 > 1 || matches2 > 1 || matches3 > 1 || matches4 > 1 || matches5 > 1 || matches6 > 1 || matches7 > 1){ 
      $('span#resultgroup1<%=pempidw2%>').css("color", "red"); 
     } 
     if(matches1 < 2 && matches2 < 2 && matches3 < 2 && matches4 < 2 && matches5 < 2 && matches6 < 2 && matches7 < 2){ 
      $('span#resultgroup1<%=pempidw2%>').css("color", "black"); 
     } 
    } 

    // and here we bind to the change event for the selects 
    // and re-call our above function. 
    $('select').on('change', getSelectedValues); 


</script> 

這是JavaScript來幫助避免在一個以上的部分進入了相同的答案的用戶。這一切都運作緩慢。

+1

你有這個問題標記爲Java,但我沒有看到任何Java在這裏。我錯過了什麼嗎? – MarsAtomic 2015-02-24 20:27:54

+1

爲什麼不存儲數據,只需使用更改處理程序進行更新,而不是每次都進行大量的DOM搜索? – charlietfl 2015-02-24 20:30:31

+6

...頁面有一千個下拉? – Brandon 2015-02-24 20:30:39

回答

0

確保您充分利用javascript/jquery語言! (也可以加快你的代碼的運行速度,但不是JavaScript本身)

這裏有很多複製/粘貼的代碼,例如

var matches7 = $('#group7 select').filter(function(){ 
return $(this).val() == '7'; 

這些增值經銷商都可以在一個方法調用傳遞不同類變量重構,以節省空間,並有利於加快節目一點。一旦你的重構的時候,你可以這樣做:

if $(this).val(){$(this).parent().css{ *set whatever css here}} 

那將是一個重大的加快,因爲你不必爲每一個類型後檢查所有值,只是班級的變量的($這個)是。

編輯:我意識到.filters()可以在DOM肆虐,請嘗試使用$("select[value=1]:checked").length而不是爲更好的整體性能

希望幫助!