从Ajax中选择HTML元素会得到jQuery的响应。

时间:2022-10-09 17:07:46

I am a programming student, I'm trying to build a simple website using HTML, JavaScripts, and jQuery for the front-end, and node.js + Express frameworks for the back-end.

我是一名编程专业的学生,我正在尝试用HTML、javascript和jQuery为前端和节点构建一个简单的网站。用于后端的js + Express框架。

In this example, I am using Ajax to get data, then append HTML codes + this data to a div element with the id = 'listFile'. The implementation works fine, I am able to see the Download and Delete button appended by Ajax.

在本例中,我使用Ajax获取数据,然后将HTML代码+该数据附加到id = 'listFile'的div元素中。实现运行良好,我可以看到Ajax附加的下载和删除按钮。

However, when I used jQuery id selector to select the delete button and make an alert, it did not work at all. It seems I cannot select the delete button implemented by Ajax.

但是,当我使用jQuery id选择器来选择delete按钮并发出警告时,它根本不起作用。似乎我不能选择Ajax实现的delete按钮。

Please explain for me why this happen, and how to fix it. Thanks!

请给我解释一下为什么会发生这种情况,以及如何解决。谢谢!

$.ajax({
    url: '/download',
    method: "get",
    success: function(data){
        for(i=1; i<data.length; i++){
            $('#listFile').append("<tr><td id='tab'><a href='#' class='list-group-item' id='"+data[i]+"' style='margin-top:5px' value='"+data[i]+"'>"+data[i]+"</a></td><td id='tab2' ><a href='#' style='width:90px' id='deleteButton' class='btn btn-danger'>Delete</a><a href='#' style='width:90px' id='downloadButton' class='btn btn-primary'>Download</a</td></tr>");
        }   
    }
});

$('#deleteButton').click(function(){
    alert("DELETED");
});

5 个解决方案

#1


2  

Change your click binding like below:

更改您的点击绑定如下:

$(document).on('click', '#deleteButton',function(){
   alert("DELETED");
});

Explanation: $('#deleteButton').click event will work only for available DOM element when window load successfully. As Delete button is created dynamically using ajax so you should use $(document).on('click', '#deleteButton',function(){ so that it works for current available DOM elements

解释:$(' # deleteButton”)。单击事件将只在窗口加载成功时对可用的DOM元素起作用。因为Delete按钮是使用ajax动态创建的,所以应该使用$(document)。在('click', '#deleteButton',function(){以便它适用于当前可用的DOM元素

Suggestion: Should use . class for multiple delete buttons instead of # id and change binding code to .deleteButton from #deleteButton

建议:应该使用。类用于多个delete按钮而不是# id,并将绑定代码从#deleteButton更改为.deleteButton

#2


0  

try this

试试这个

 $.ajax({
        url: '/download',
        method: "get",
        success: function(data){
            for(i=1; i<data.length; i++){
                $('#listFile').append("<tr><td id='tab'><a href='#' class='list-group-item' id='"+data[i]+"' style='margin-top:5px' value='"+data[i]+"'>"+data[i]+"</a></td><td id='tab2' ><a href='#' style='width:90px' id='deleteButton' class='btn btn-danger'>Delete</a><a href='#' style='width:90px' id='downloadButton' class='btn btn-primary'>Download</a</td></tr>");
            }   
 xyz();
        }

    });
    function xyz(){
       $('#deleteButton').click(function(){
           alert("DELETED");
       });
    }

#3


0  

This is all about having the ".click" method bound to the new item you created. .click is setup to look at the dom on first load but will not attach any newly created buttons to the click event. By using ".on" you are telling your script to look at whatever you are targeting and then attach whatever event to it.

这都是关于"。单击“方法绑定到您创建的新项。.click is setup在第一次加载时查看dom,但是不会将任何新创建的按钮附加到单击事件。通过使用”。在“您正在告诉您的脚本查看您的目标,然后附加任何事件到它。”

$(".container").on("event",".target",function(){
    //do something
});

#4


0  

Your jquery selector is based on an id of "deleteButton." ID's should be unique within a document but your code will generate multiple links with ID=deleteButton.

您的jquery选择器基于“deleteButton”的id。ID在文档中应该是唯一的,但是您的代码将使用ID=deleteButton生成多个链接。

Consider adding a class to your delete button and then using that as the selector:

考虑向delete按钮添加一个类,然后使用它作为选择器:

$.ajax({
    url: '/download',
    method: "get",
    success: function(data){
        for(i=1; i<data.length; i++){
            $('#listFile').append("<tr><td id='tab'><a href='#' class='list-group-item' id='"+data[i]+"' style='margin-top:5px' value='"+data[i]+"'>"+data[i]+"</a></td><td id='tab2' ><a href='#' style='width:90px' id='deleteButton-"+data[i]+"' class='deleteButton btn btn-danger'>Delete</a><a href='#' style='width:90px' id='downloadButton' class='btn btn-primary'>Download</a</td></tr>");
        }   
    }
xyz();
});
function xyz(){
   $('.deleteButton').click(function(){
       alert("DELETED");
   });
}

Note that I've added a class and changed the id of each element in your list to be unique by appending data[i] to its ID. Note that I've also changed the "#" in your jQuery selector to "." - this changes the selector from finding element with id=deleteButton to finding element with class=deleteButton.

注意,我添加了一个类,并通过将数据[I]附加到id中,将列表中的每个元素的id更改为惟一的。-这将选择器从使用id=deleteButton查找元素更改为使用class=deleteButton查找元素。

Once you've detected that click, it's then easy to capture the id of the specific item that's being clicked using $(this).attr('id').

一旦您发现了单击,那么就很容易捕获使用$(this).attr('id')单击的特定项的id。

#5


0  

You need to use Event Delegation. This means that instead of attaching the click event on the delete button itself, you attach it on any of its ascendent. Now whenever the button is clicked, due to the Event Bubbling process, the event is moved all the way up to the DOM. As soon as the event reaches the target element which was listening for that event, it will execute the code that you wrote.

您需要使用事件委托。这意味着您不必将单击事件附加到delete按钮本身上,而是将它附加到它的任何一个上升项上。现在,每当单击按钮时,由于事件冒泡过程,事件将一直移动到DOM。一旦事件到达监听该事件的目标元素,它将执行您所编写的代码。

Enough talk, here's how you can do it:

说得够多了,你可以这么做:

$('document').on("click", ".deleteButton" function() {
    alert("DELETED");
});

Note that I've replaced the #deleteButton with .deleteButton since an ID MUST be unique throughout the document, therefore, you must replace the replace the html markup <button id='deleteButton'> with <button class='deleteButton'> in the append method.

请注意,我已经用.deleteButton替换了#deleteButton,因为在整个文档中ID必须是惟一的,因此,您必须在append方法中使用

There are a couple of more things that you should note down.

还有几件事你应该记下来。

  1. Once your ajax request has completed. You are jumping into the DOM to select the element with the ID of #listFile which is being done inside a loop which is really bad for performance issues.
  2. 一旦ajax请求完成。您将跳到DOM中,选择ID为#listFile的元素,该元素在循环中执行,这对性能问题非常不利。

Solution Store the: element reference before you execute the loop.

解决方案在执行循环之前存储:元素引用。

success: function() {
    var listFile = $('#listFile');
    for (...) {
        listFile.append(....)
    }
}
  1. Instead of appending the elements inside a loop which will cause the DOM to reflow every single time you append an element, consider using DocumentFragment. https://developer.mozilla.org/en/docs/Web/API/DocumentFragment
  2. 不要在每次添加元素时都将元素添加到循环中,从而导致DOM回流,而是考虑使用DocumentFragment。https://developer.mozilla.org/en/docs/Web/API/DocumentFragment

Hope that makes sense, feel free to ask any questions! :-)

希望有道理,有问题尽管问!:-)

#1


2  

Change your click binding like below:

更改您的点击绑定如下:

$(document).on('click', '#deleteButton',function(){
   alert("DELETED");
});

Explanation: $('#deleteButton').click event will work only for available DOM element when window load successfully. As Delete button is created dynamically using ajax so you should use $(document).on('click', '#deleteButton',function(){ so that it works for current available DOM elements

解释:$(' # deleteButton”)。单击事件将只在窗口加载成功时对可用的DOM元素起作用。因为Delete按钮是使用ajax动态创建的,所以应该使用$(document)。在('click', '#deleteButton',function(){以便它适用于当前可用的DOM元素

Suggestion: Should use . class for multiple delete buttons instead of # id and change binding code to .deleteButton from #deleteButton

建议:应该使用。类用于多个delete按钮而不是# id,并将绑定代码从#deleteButton更改为.deleteButton

#2


0  

try this

试试这个

 $.ajax({
        url: '/download',
        method: "get",
        success: function(data){
            for(i=1; i<data.length; i++){
                $('#listFile').append("<tr><td id='tab'><a href='#' class='list-group-item' id='"+data[i]+"' style='margin-top:5px' value='"+data[i]+"'>"+data[i]+"</a></td><td id='tab2' ><a href='#' style='width:90px' id='deleteButton' class='btn btn-danger'>Delete</a><a href='#' style='width:90px' id='downloadButton' class='btn btn-primary'>Download</a</td></tr>");
            }   
 xyz();
        }

    });
    function xyz(){
       $('#deleteButton').click(function(){
           alert("DELETED");
       });
    }

#3


0  

This is all about having the ".click" method bound to the new item you created. .click is setup to look at the dom on first load but will not attach any newly created buttons to the click event. By using ".on" you are telling your script to look at whatever you are targeting and then attach whatever event to it.

这都是关于"。单击“方法绑定到您创建的新项。.click is setup在第一次加载时查看dom,但是不会将任何新创建的按钮附加到单击事件。通过使用”。在“您正在告诉您的脚本查看您的目标,然后附加任何事件到它。”

$(".container").on("event",".target",function(){
    //do something
});

#4


0  

Your jquery selector is based on an id of "deleteButton." ID's should be unique within a document but your code will generate multiple links with ID=deleteButton.

您的jquery选择器基于“deleteButton”的id。ID在文档中应该是唯一的,但是您的代码将使用ID=deleteButton生成多个链接。

Consider adding a class to your delete button and then using that as the selector:

考虑向delete按钮添加一个类,然后使用它作为选择器:

$.ajax({
    url: '/download',
    method: "get",
    success: function(data){
        for(i=1; i<data.length; i++){
            $('#listFile').append("<tr><td id='tab'><a href='#' class='list-group-item' id='"+data[i]+"' style='margin-top:5px' value='"+data[i]+"'>"+data[i]+"</a></td><td id='tab2' ><a href='#' style='width:90px' id='deleteButton-"+data[i]+"' class='deleteButton btn btn-danger'>Delete</a><a href='#' style='width:90px' id='downloadButton' class='btn btn-primary'>Download</a</td></tr>");
        }   
    }
xyz();
});
function xyz(){
   $('.deleteButton').click(function(){
       alert("DELETED");
   });
}

Note that I've added a class and changed the id of each element in your list to be unique by appending data[i] to its ID. Note that I've also changed the "#" in your jQuery selector to "." - this changes the selector from finding element with id=deleteButton to finding element with class=deleteButton.

注意,我添加了一个类,并通过将数据[I]附加到id中,将列表中的每个元素的id更改为惟一的。-这将选择器从使用id=deleteButton查找元素更改为使用class=deleteButton查找元素。

Once you've detected that click, it's then easy to capture the id of the specific item that's being clicked using $(this).attr('id').

一旦您发现了单击,那么就很容易捕获使用$(this).attr('id')单击的特定项的id。

#5


0  

You need to use Event Delegation. This means that instead of attaching the click event on the delete button itself, you attach it on any of its ascendent. Now whenever the button is clicked, due to the Event Bubbling process, the event is moved all the way up to the DOM. As soon as the event reaches the target element which was listening for that event, it will execute the code that you wrote.

您需要使用事件委托。这意味着您不必将单击事件附加到delete按钮本身上,而是将它附加到它的任何一个上升项上。现在,每当单击按钮时,由于事件冒泡过程,事件将一直移动到DOM。一旦事件到达监听该事件的目标元素,它将执行您所编写的代码。

Enough talk, here's how you can do it:

说得够多了,你可以这么做:

$('document').on("click", ".deleteButton" function() {
    alert("DELETED");
});

Note that I've replaced the #deleteButton with .deleteButton since an ID MUST be unique throughout the document, therefore, you must replace the replace the html markup <button id='deleteButton'> with <button class='deleteButton'> in the append method.

请注意,我已经用.deleteButton替换了#deleteButton,因为在整个文档中ID必须是惟一的,因此,您必须在append方法中使用

There are a couple of more things that you should note down.

还有几件事你应该记下来。

  1. Once your ajax request has completed. You are jumping into the DOM to select the element with the ID of #listFile which is being done inside a loop which is really bad for performance issues.
  2. 一旦ajax请求完成。您将跳到DOM中,选择ID为#listFile的元素,该元素在循环中执行,这对性能问题非常不利。

Solution Store the: element reference before you execute the loop.

解决方案在执行循环之前存储:元素引用。

success: function() {
    var listFile = $('#listFile');
    for (...) {
        listFile.append(....)
    }
}
  1. Instead of appending the elements inside a loop which will cause the DOM to reflow every single time you append an element, consider using DocumentFragment. https://developer.mozilla.org/en/docs/Web/API/DocumentFragment
  2. 不要在每次添加元素时都将元素添加到循环中,从而导致DOM回流,而是考虑使用DocumentFragment。https://developer.mozilla.org/en/docs/Web/API/DocumentFragment

Hope that makes sense, feel free to ask any questions! :-)

希望有道理,有问题尽管问!:-)