【问题标题】:How can i get data-id value(id) store in Array using JavaScript?如何使用 JavaScript 将数据 ID 值(ID)存储在数组中?
【发布时间】:2021-01-08 20:36:34
【问题描述】:

如何使用 JavaScript 获取 ID 号(数据 ID)。我正在使用 sortable.min.js 进行拖放。我想获取#drop 表内的td ID(data-id) 并将其存储到数组中(排序)?

table.html

   <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Story</th>
            </tr>
        </thead>
        <tbody id="drop" class="sortables">
            <tr>
                <td data-id="67">67</td>
                <td>this is test post for (news2)d</td>
            </tr>
            <tr>
                <td data-id="59">59</td>
                <td>how to use custom fonts in dja</td>
            </tr>
           <tr>
               <td data-id="51">51</td>
               <td>how can i merge two forms fiel</td>
            </tr>
        </tbody>
    </table>

    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Story</th>
            </tr>
        </thead>
        <tbody id="drag" class="sortables">

        </tbody>
    </table>

script.js

   new Sortable(drag, {
        group: '.sortables',
        animation: 150,
    });


    new Sortable(drop, {
        group: '.sortables',
        animation: 150,
        onChange: function (e, tr) {
            sort = [];
            $("#drog").children().each(function () {
                sort.push({ 'id': $(this).data('id') })
            });
            console.log(sort)
        },
    });

【问题讨论】:

  • 错字$("#drog").children() => $("#drop").children()
  • 请你解释一下我如何将它定义到我的函数中,因为我是 JavaScript 的初学者,你能通过更新我的代码中的代码来回答吗
  • 换行:$("#drog").children().each(function () {改为$("#drop").children().each(function () {
  • 是的,我也试试这个,但我得到 undefined 或空数组

标签: javascript jquery bootstrap-4 sortablejs


【解决方案1】:

正如所指出的,您的选择器中有一个错字:

$("#drog")

应该是:

$("#drop")

你也可以考虑以下。

new Sortable(drag, {
  group: '.sortables',
  animation: 150,
});

new Sortable(drop, {
  group: '.sortables',
  animation: 150,
  onChange: function (e, tr) {
    var sort = [];
    $("#drop > tbody > tr").each(function (i, row) {
      sort.push({ 'id': $("td:first", row).data('id') });
    });
    console.log(sort);
  },
});

您之前的代码针对的是#drop 中的children,它们是&lt;TR&gt; 元素并且没有Data 属性。

新代码针对每行的第一个 &lt;TD&gt; 元素。此元素具有 Data 属性。

【讨论】:

  • 它得到的是空数组。它没有得到 ID
  • 你的代码是完整的$("#drop").each(function (i, row) { 这个代码对我有用。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 2023-03-05
  • 1970-01-01
  • 2012-11-22
  • 2011-12-12
  • 2019-03-11
相关资源
最近更新 更多