javascript - 使用 Jquery 选择动态给定的 Id 不起作用

标签 javascript jquery css eventhandler

我必须为大学建立一个网站,在其中我从数据库中加载数据到表中。 我的 table 看起来像这样:https://dl.dropboxusercontent.com/u/6265197/Table.png

首先,我从数据库加载内容并创建一个表。

...
$.each(data, function (index, item) {
var counter = index;
counter++;
...
table += '<td><a href="#" ' + 'id=edit' + counter + '><img src="img/edit-icon.png"' + '</a> </td>';
table += '<td><a href="#" ' + 'id=delete' + counter + '><img src="img/delete-icon.png"' + ' ></a> </td>';
...

我为按钮提供了正确有效的唯一 ID。

我的意图是,如果按下“edit1”,我可以抓取“name1”来使用它并在数据库中找到它。

我尝试过这个例子,它只在控制台上给我一个空字符串。

...
for (var x = 1; x <= 2; x++) {
    $('body').on('click', '#edit' + x, function () {
        console.log($('#name' + x).text());
    });
...

这个基本上可以工作......并在控制台上给我字符串(A Long Way Down)。

...
for (var x = 1; x <= 2; x++) {
    $('body').on('click', '#edit' + x, function () {
        console.log($('#name1').text());
    });
...

希望你能给我答案。

问候安德烈亚斯

最佳答案

你应该学习Event Delegation

您可以使用自定义data-*属性来设置值。然后使用.data()来获取它。

示例代码

table += '<td><a href="#" class="edit" data-id="' + counter + '"><img src="img/edit-icon.png"' + '</a> </td>';
table += '<td><a href="#" class="delete" data-id="' + counter + '"><img src="img/delete-icon.png"' + ' ></a> </td>';

$(document).on('click', ".edit", function(event){
    event.preventDefault();
    var id = $(this).data('id');
    var text = $('#name' + id).text()
    console.log(text);
});

您应该使用最接近的静态容器来代替文档

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

关于javascript - 使用 Jquery 选择动态给定的 Id 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24486467/

相关文章:

css - 如何在 CSS 中将颜色定义为变量?

javascript - 浏览器控制台错误

javascript - jQuery或JavaScript年龄计算器

javascript - 元素上的 jQuery.ready() 等效事件监听器?

java - jqgrid解析器错误

Jquery datepicker 作为弹出窗口?

css - TailwindCSS 是如何实现断点前缀功能的?

javascript - Bootstrap 2 或 3 Modal 中的 Kendo Grid - IE 过滤器不起作用

javascript - 谷歌Firestore : Filter documents where sub-key is between given value

javascript - Windows 8/8.1 JQuery 上的 IE 11 is() 和 has() 不包含可滚动 div 的滚动条