javascript - 无法使用 javascript 获取动态删除/编辑 HTML 表的值

标签 javascript html node.js

我正在尝试编写一段代码来处理动态 HTML 表格的删除或编辑。我用 google 和 stackoverflow 搜索了这个问题,我看到了很多样本​​,但没有一个能正常工作。

这是我的代码:

服务器.js

router.get('/bookShow', (req, res) => {
    bookModel.find({isDeleted : false}).sort('-pageCount').exec((err, data) => {
        if (data) {
            res.send(data);
        }
    });
});

数据库中的 BookModel:

enter image description here

bookShow.html

<script>
    $(document).ready(() => {
        $.getJSON('/bookShow', (json) => {
            var tr;
            for (var i = 0; i < json.length; i++) {
                tr = $('<tr/>');
                tr.append("<td>" + "<button class='deleteButton'>" + "<i class='material-icons'>delete</i></button>" + "</td>");
                tr.append("<td>" + "<button class='editButton'>" + "<i class='material-icons'>edit</i></button>" + "</td>");
                tr.append("<td>" + json[i].pageCount + "</td>");
                tr.append("<td>" + json[i].name + "</td>")
                $('table').append(tr);
            }
        });

        $(document).on('click', '.deleteButton', () => {
            console.log($(this));
        })
    });  
</script>

问题:正如在 bookShow.html 中看到的那样,每当单击 .deleteButton 时我都声明了一个事件监听器。但我无法访问该表行的其他字段。例如,当我点击 Behzad 的删除按钮时,我无法收到书名和页数的通知。

enter image description here

最佳答案

通过使用 ES6 的箭头函数 () => {} this使用 function 不再是您过去喜欢的东西了.这是window ,因为它们的词法范围绑定(bind)的性质。不再是 jQuery 对 DOM 元素“this”的表示。

$(this) =
jQuery.fn.init [Window] by usign Arrow function () => {}
jQuery.fn.init [button.deleteButton] by using Function function () {}

因此您的解决方案是使用标准 $(document).on('click', '.deleteButton', function() {

或添加 click关于创建按钮 - 这可以通过使您的按钮成为事件内存中的 jQuery 元素来实现 $('<button>', {on:{click(){}}, appendTo:'selector'})而不是 HTML 字符串文字。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

这是一个翻拍:

const json = [ // You use getJSON, I'll use this for my demo
{"name": "King of the Jungle","pageCount": 543},
{"name": "The Things I've Done","pageCount": 198}
];

jQuery($ => {

  // $.getJSON

  $('table').append(json.map((book, i) => 
    $('<tr>', {
      html: `
        <td>${i+1}</td>
        <td>${book.name}</td>
        <td>${book.pageCount}</td>
      `,
      append: [       // or use prepend
        $('<td>', {
          append: $('<button>', {
            class: "buttonEdit",
            html: "<i class='material-icons'>edit</i>",
            on: {
              click() { // Same as using `click: function () {`
                console.log(`Editing ${book.name} by:`, this); // this = <button>
              }
            }
          })
        }),
        $('<td>', {
          append: $('<button>', {
            class: "buttonDelete",
            html: "<i class='material-icons'>delete</i>",
            on: {
              click() {
                console.log(`Deleting ${book.name} by:`, this);
              }
            }
          })
        }),        
      ]
    })
  ));

  // END $.getJSON

});
table {
  width: 100%;
}

td {
  border: 1px solid #ddd;
}
<table></table>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>

关于javascript - 无法使用 javascript 获取动态删除/编辑 HTML 表的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52022267/

相关文章:

javascript - 如何使用 JavaScript 或 moment 从 2 个日期创建新的格式化日期

javascript - 如何判断 HTTP 表单是否已提交?

c# - 默认值设置为 0 的输入在没有 0 的情况下呈现

html - 如何使用 ngFor 遍历 Map 并在 Angular 2+ 中按顺序在 html 上显示它们?

node.js - 无法连接到 ubuntu xenial 上的 nodejs

node.js - nodejs - 下载的图像已损坏

javascript - KnpLabs/snappy bundle (wkhtmltopdf) 不呈现 Chart.js 图表

javascript - 点沿路径插值平移函数

javascript - 替换内置属性的 IE8 属性枚举(例如 `toString` )

javascript - Node JS,传统数据结构? (例如 Set 等),诸如 Java.util 之类的 Node ?