【问题标题】:DataTable with button, append element to list带按钮的 DataTable,将元素附加到列表
【发布时间】:2018-04-15 14:52:43
【问题描述】:

我正在使用来自 jquery 的数据表插件,并在我的数据表中添加了一个按钮。按下按钮时,我想将元素标题添加到无序列表元素中。

在下面找到我的最小可行示例:

const results = {
  "generalInfo": [{
      "title": "title1",
      "permalink": "www.link.com",
      "manufacturer": "manufacturer1",
      "img": "https://images-na.ssl-images-test.com/images/asdfIdR/5adf1vELadfZeiMML.jpg",
      "curreny": "$",
      "price": "64.00",
      "availability": "Usually ships in 24 hours",
    },
    {
      "title": "title2",
      "permalink": "www.link.com",
      "manufacturer": "manufacturer2",
      "img": "https://images-na.ssl-images-test.com/images/I/51adfkLhadsfgACH0L.jpg",
      "curreny": "$",
      "price": "59.99",
      "availability": "Usually ships in 24 hours",
    }
  ]
}

//transform data set
let dataSet = results.generalInfo.map((item, i) => [
  i + 1,
  `<img src="${item.img}" alt="${item.title}" height="42" width="42">
                 <a href="<?php the_permalink();?>">
                     ${item.title}
                 </a>`,
  item.manufacturer,
  `<div>${item.currency} ${item.price}</div>`,
  item.availability,
  `<button id="addButton" type="button" onClick="${this.addToResults.bind(item)}">
                    Add
                </button>`,
  `<a class="btn btn-primary" target="_blank" role="button">
                    Buy
                </a>`
])

$('#table_id').DataTable({
  data: dataSet,
  destroy: true,
  columns: [{
      title: "#"
    },
    {
      title: "Title"
    },
    {
      title: "Manufacturer"
    },
    {
      title: "Price"
    },
    {
      title: "Availability"
    },
    {
      title: ""
    },
    {
      title: ""
    }
  ]
})

function addToResults(item) {

  $("ul").append(`<li>${item.title}</li>`);

}
<link href="http://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />

<table id="table_id" class="display" style="width:100%"></table>

<h1>Results:</h1>
<ul>

</ul>

当我按下按钮时,我收到一条错误消息并且没有附加文本。

任何建议我做错了什么?

【问题讨论】:

    标签: javascript jquery datatables


    【解决方案1】:

    与其将项目绑定到您的内联 JS 处理程序(我真的不鼓励人们这样做,因为内联 JS 实在是太糟糕了),您真正想要的只是对 results.generalInfo 数组的引用,这样您就可以从中取出正确的物品。

    在这种情况下,这就足够了:

    1. 为您的按钮分配一个类,而不是一个 ID(ID 必须是唯一的),例如 &lt;button class="addButton" ... /&gt;
    2. 存储对相关项目的不变引用。这就像将索引存储在 data- 属性中一样简单,例如&lt;button data-item-index="${i}" class="addButton" ... /&gt;
    3. 将单击事件处理程序绑定到该类
    4. 在点击事件处理程序中,从data-item-index 检索值并将其用作访问results.generalInfo 中的原始项目的键。请记住 data- 属性总是返回 string ,因此使用 + 操作将其强制转换为整数:

      $('#table_id').on('click', 'button.addButton', function() {
        const itemIndex = +$(this).data('item-index');
        const item = results.generalInfo[itemIndex];
        $("ul").append(`<li>${item.title}</li>`);
      });
      

    请参阅下面的概念验证 sn-p:

    const results = {
      "generalInfo": [{
          "title": "title1",
          "permalink": "www.link.com",
          "manufacturer": "manufacturer1",
          "img": "https://images-na.ssl-images-test.com/images/asdfIdR/5adf1vELadfZeiMML.jpg",
          "curreny": "$",
          "price": "64.00",
          "availability": "Usually ships in 24 hours",
        },
        {
          "title": "title2",
          "permalink": "www.link.com",
          "manufacturer": "manufacturer2",
          "img": "https://images-na.ssl-images-test.com/images/I/51adfkLhadsfgACH0L.jpg",
          "curreny": "$",
          "price": "59.99",
          "availability": "Usually ships in 24 hours",
        }
      ]
    }
    
    //transform data set
    let dataSet = results.generalInfo.map((item, i) => [
      i + 1,
      `<img src="${item.img}" alt="${item.title}" height="42" width="42">
                     <a href="#">
                         ${item.title}
                     </a>`,
      item.manufacturer,
      `<div>${item.currency} ${item.price}</div>`,
      item.availability,
      `<button class="addButton" type="button" data-item-index="${i}">
                        Add
                    </button>`,
      `<a class="btn btn-primary" target="_blank" role="button">
                        Buy
                    </a>`
    ]);
    
    $('#table_id').on('click', 'button.addButton', function() {
      const item = results.generalInfo[+$(this).data('item-index')];
      $("ul").append(`<li>${item.title}</li>`);
    });
    
    $('#table_id').DataTable({
      data: dataSet,
      destroy: true,
      columns: [{
          title: "#"
        },
        {
          title: "Title"
        },
        {
          title: "Manufacturer"
        },
        {
          title: "Price"
        },
        {
          title: "Availability"
        },
        {
          title: ""
        },
        {
          title: ""
        }
      ]
    });
    <link href="http://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
    
    <table id="table_id" class="display" style="width:100%"></table>
    
    <h1>Results:</h1>
    <ul>
    
    </ul>

    【讨论】:

    • 感谢您的回答!还有没有办法通过点击监听器上的函数调用直接将整个项目传递给点击监听器?
    • @mrquad 整个项目已经分配给点击处理程序中的item 常量。
    • 最后一个问题,为什么你把点击监听器放在桌子上而不是直接放在按钮上。如,$('#table_id') 而不是 $('.addButton') 提前谢谢您的评论!
    • @mrquad 其实是为了捕捉事件冒泡。由于您已将按钮动态添加到表中,因此您无法将单击事件直接绑定到按钮,因为它们在运行时不可用。相反,您将点击事件绑定到表格本身,并简单地检查点击事件是否从按钮元素冒泡(因此是.on() 方法的第二个参数)。
    猜你喜欢
    • 2017-06-23
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2014-06-10
    • 2017-12-18
    • 2021-10-06
    • 2015-02-05
    相关资源
    最近更新 更多