如何使用jQuery.ajax动态修改添加的html
How can I modify dynamically added html with jQuery.ajax?
我在jQuery中有一个ajax调用,它在我的站点中返回并插入一些HTML。在同一个调用中,在成功回调中,我想对返回的html"做一些事情"。
一些代码(简化):
$.ajax({
url: "some_url.php",
type: 'POST',
dataType: 'json',
data: some_data,
success: function(response){
myAsyncAjaxInsertHtmlFunction(response); // 1. This function is an ajaxcall which inserts HTML dynamically
$(newlyAddedSelector + ' input').each(function(){ // 2. Here I want to iterate over those dynamically added html elements
doStuffWithNewlyAddedHtml(this.value);
});
}
});
问题是,当代码执行到达第2点时,动态添加的html还没有加载。我知道async:false存在,但这不是我想走的路线。
你应该如何处理这种情况,我可以想象这种情况很常见?
您可以使用fct().done()等待ajax执行完毕,然后再转到第二个进程
function ajax1() {
return $.ajax({
url: "someUrl",
...
});
}
ajax1().done(function(){
// the code here will be executed when ajax requests resolve.
});
编辑的
var insered = false;
$.ajax({
url: "some_url.php",
type: 'POST',
dataType: 'json',
data: some_data,
success: function(response){
myInsertHtmlFunction(response); // 1. This function inserts HTML dynamically
insered = true;
},
complete: function(){
if( insered == true ) {
$(newlyAddedSelector + ' input').each(function(){ // 2. Here I want to iterate over those dynamically added html elements
doStuffWithNewlyAddedHtml(this.value);
});
}
}
});
你可以插入你的html成功地做你的最后的东西在完整的方法。
除非您的myInsertHtmlFunction
函数执行async
,否则您的代码应该可以工作,因为添加&删除HTML元素总是同步的。
但是,如果您的应用程序逻辑也修改HTML,这取决于一些新添加的元素的加载状态,例如,如果新添加的图像完成加载,则添加div,那么您的代码将失败。
这完全取决于myInsertHtmlFunction
函数。
相关文章:
- 使用jQuery根据动态生成的html动态添加html
- 如何使用javascript选择字符串的部分,添加html标记或删除部分
- 单击按钮添加HTML表单
- 如何添加html<br>标记转换为javascript
- 动态添加 HTML 元素后创建 jQuery 事件
- 在具有特定ID的DIV中使用JavaScript动态添加HTML元素
- 在前面的输入元素之前添加html输入元素
- 程序添加html后点击不工作
- 使用appendchild或其他方法向ul添加html代码而不是纯文本
- 如何在JS函数中添加HTML代码
- Jquery从另一个页面添加HTML
- 如何在不添加html脚本标记的情况下使用google-maps-api-v3
- 正在尝试向jQuery对象添加HTML类属性
- 使用“添加用户”按钮添加HTML字段
- 在 JavaScript 中的 textNode 中添加 html
- jquery动态添加HTML字段遇到了神秘的问题
- AngularJS 如何动态添加 HTML 并绑定到控制器
- 使用 js 添加 HTML 元素
- 在 JavaScript 切换中添加 html / css
- 如何在 tinymce 的第一段中添加 html 链接