簡體   English   中英

數據沒有被推送到數組

[英]Data isn't getting pushed to array

我已經能夠在表的每一行中顯示JSON數據(本地文件),並且當選中數據的相應復選框時,我想將這些選定的值壓入數組。 最終目標是在div中顯示該數組,但是直到我看到該數組已被填充為止。

JS代碼段:

($("#km-table-id tbody tr")).append($("<input />", {"type": "checkbox"}).addClass("checkbox-class"));

let table = $("#km-table-id").DataTable();
    let favesArr = [];

    $(".checkbox-class").on("click", "tr", function() {
      let data = table.row(this).data();
      for (var i = 0; i < favesArr.length; i++) {
        favesArr.push($(data).text());
        $("#myFave.hs-gc-header").append(favesArr[i]);
      }      
      console.log(data); // this was showing the selected data a short time ago, but not anymore  

    });

    console.log(favesArr); // only showing empty

首先,最后一行將始終打印一個空數組,因為您僅將其填充到事件處理程序中。

其次,您將i < favesArr.length用作循環條件。 如果代碼的其他部分未填寫,則favesArr此處favesArr空。 因此,循環體永遠不會執行。 您可能在這里想要data.length

最后但並非最不重要的一點,您可能只想將data[i]而不是整個數組推入favesArray

我建議您捕獲是否已選中該復選框。 您可以通過獲取數據索引來檢查項目是否已在數組中。

不確定您的HTML是什么樣的...

 (function($) { $.fn.appendText = function(text) { return this.text(this.text() + text); }; $.fn.appendHtml = function(html) { return this.html(this.html() + html); }; })(jQuery); const $table = $('#km-table-id'); $table.find('tbody tr').append($("<input>", { type: 'checkbox', class : 'checkbox-class'})); let table = $table.DataTable(); let favesArr = []; $table.on('click', '.checkbox-class', function(e) { let data = table.row(this.parentNode).data(), checked = $(this).is(':checked'), dataIndex = favesArr.indexOf(data); if (checked) { if (dataIndex === -1) { favesArr.push(data); // Add item } } else { if (dataIndex > -1) { favesArr.splice(dataIndex, 1); // Remove item } } $('#myFave.hs-gc-header').appendHtml('>> ' + favesArr.map(x => x.join(', ')).join('; ') + '<br/>'); }); 
 body { background: #666; } .table-wrapper { background: #fff; width: 80%; margin: 0 auto; margin-top: 1em; padding: 0.25em; } #myFave.hs-gc-header { background: #fff; width: 81%; margin: 0 auto; margin-top: 0.5em; height: 5em; overflow: scroll; } 
 <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <div class="table-wrapper"> <table id="km-table-id"> <thead> <tr> <th>A</th><th>B</th><th>C</th> </tr> </thead> <tbody> <tr> <td>1</td><td>2</td><td>3</td> </tr> <tr> <td>4</td><td>5</td><td>6</td> </tr> <tr> <td>7</td><td>8</td><td>9</td> </tr> </tbody> </table> </div> <div id="myFave" class="hs-gc-header"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM