2015-01-09 23 views
0

我需要你的幫助。我有一個jquery代碼,它在第一次加載頁面後運行良好,第二步選中複選框。在後臺函數updateSg(opts)中調用了導致Json的submit.php。jQuery在頁面加載的同時運行

但我想解決當我打開頁面時,複選框輸入標記從URL獲取檢查值,並複選框被選中,但jQuery代碼不運行。我必須取消選中並再次檢查運行的代碼。

你可以給我一個幫助,代碼與頁面加載在一起執行。

感謝, 姿態

<div id="result"></div> 
<div id="filter"> 
    <h2>Filter</h2> 
    <div> 
    <input type="checkbox" id="sg" name="sg" checked> 
    <label for="sg">Something</label> 
    </div> 
</div> 
<script src="http://code.jquery.com/jquery-latest.js"></script> 

<script> 
    var getsg = "something"; 

    function makeTable(data){ 
     var tbl_body = ""; 
     $.each(data, function(k,v) { 
     tbl_body += getsg; 
     }) 
     return tbl_body; 
    } 

    function getSgFilterOptions(){ 
    var opts = []; 
    $checkboxes.each(function(){ 
     if(this.checked){ 
     opts.push(this.name); 
     } 
    }); 
    return opts; 
    } 

    function updateSg(opts){ 
    $.ajax({ 
     type: "POST", 
     url: "submit.php", 
     dataType : 'json', 
     cache: false, 
     data: {filterOpts: opts}, 
     success: function(records){ 
     $('div#result').html(makeTable(records)); 
     } 
    }); 
    } 

    var $checkboxes = $("input:checkbox"); 
    $checkboxes.on("change", function(){ 
    var opts = getSgFilterOptions(); 
    updateSg(opts); 
    }); 

    updateSg(); 

    </script> 
+0

您使用的是什麼瀏覽器?檢查的屬性應該做的伎倆。 – 2015-01-09 18:32:18

+0

我正在使用chrome,但它當然應該是一個獨立於瀏覽器的解決方案。 我不明白我如何使用這個技巧。 – Atti 2015-01-09 19:43:35

回答

1

您應檢查是否複選框以第一名檢查。

接下來,您的updateSg()函數在頁面加載時不提供ajax的postData(因此filterOpts爲空)。

試試這個:

<script> 
    var getsg = "something"; 
    var $checkboxes = $("input:checkbox"); 

    function makeTable(data){ 
     var tbl_body = ""; 
     $.each(data, function(k,v) { 
      tbl_body += getsg; 
     }); 
     return tbl_body; 
    } 

    function callAjax(opts){ 
     $.ajax({ 
      type: "POST", 
      url: "submit.php", 
      dataType : 'json', 
      cache: false, 
      data: {filterOpts: opts}, 
      success: function(records){ 
       $('div#result').html(makeTable(records)); 
      } 
     }); 
    } 

    $checkboxes.on("change", function(){ 
     getSgFilterOptions(); 
    }); 

    function getSgFilterOptions(){ 
     if($checkboxes.length){ 
      var opts = []; 
      $checkboxes.each(function(){ 
       if(this.checked){ 
        opts.push(this.name); 
       } 
      }); 
      callAjax(opts); 
     } 
    } 

    getSgFilterOptions(); 

</script> 
+0

它似乎正常工作。 感謝您的快速幫助。 – Atti 2015-01-10 08:57:20

相關問題