Asynchronous operations add nodes dynamically, causing global binding events or obtaining elements to the added nodes in the code to be invalid. What is the problem? This article mainly introduces to you the detailed explanation of dynamically adding node instances of JQuery Ajax asynchronous operation. Friends who are interested can refer to it. I hope it can help you.
$(function () { var IP = '...'; // 页面中的默认编号起始值 和 公用IP前缀 showData(); function showData() { if ($('.content')) $('.content').remove(); $.ajax({ url:IP + '/get', type:'get', success:function (data) { var newInfo = ''; if(!data) return alert('对不起,没有数据可供操作!'); newInfo +='<p class="btnBox">' + '<a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="remove">删除</a>' + '<a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="change">修改</a>' + '</p>'; });$('body').append(newInfo); }, error:function (err) { alert(err); } }); } } //这是一段很明显的通过JQuery-ajax前后台交互并动态添加的代码; //但是,如果你在该方法(showData())外面来给上述动态添加的a标签添加事件或者获取值的时候可能会出现无效的情况: $('.remove').click(function(){ alert('这是删除按钮!'); }); //页面中则不会弹出(这是删除按钮!)的弹框;
So, where is the problem?
In fact, the process of ajax obtaining data from the background and displaying it on our page is asynchronous. That is to say, when we use ajax to obtain the value from the background, the code after ajax is executed continuously. Instead of waiting for you to complete ajax acquisition and creation of nodes before continuing to execute. This is the mechanism of asynchronous requests. How do we solve this problem:
$(function () { var IP = '...'; // 页面中的默认编号起始值 和 公用IP前缀 showData(); function showData() { if ($('.content')) $('.content').remove(); $.ajax({ url:IP + '/get', type:'get', success:function (data) { var newInfo = ''; if(!data) return alert('对不起,没有数据可供操作!'); newInfo +='<p class="btnBox">' + '<a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="remove">删除</a>' + '<a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="change">修改</a>' + '</p>'; });$('body').append(newInfo); // 当动态添加节点完成之后再给其中的按钮绑定事件 $('.remove').click(function(){ alert('这是删除按钮!'); }); }, error:function (err) { alert(err); } }); } }
Change the code of binding events to inside ajax, so that after the dynamic addition is completed and then bind events to the buttons, we can achieve the effect we need. This is the asynchronous mechanism of ajax
Related recommendations:
Detailed explanation of jQuery’s ability to dynamically add nodes and traverse nodes
Mysql cluster add node horizontal expansion
The above is the detailed content of Detailed explanation of JQuery Ajax asynchronous operation of dynamically adding node instances. For more information, please follow other related articles on the PHP Chinese website!