【发布时间】:2018-03-15 14:51:20
【问题描述】:
让我举一个例子来说明这一点
<div class="main_div">
<div class="moday">
</div>
<button class="add_main">Add</button>
</div>
我们已经绑定了 add_main 类,点击添加按钮时执行的函数体如下所示
$.ajax({
type: "POST",
url : "url",
dataType : 'json',
data : {
'param1' : "param1value"
},
beforeSend: function(jqXHR , settings ){},
success: function(response){
// the response is json object.
$(this).closest('.main_div').html('<div class="inner_data_section"></div>');
// I have to assign the response data (that is json object ) to inner_data_seciton.
$(this).closest('.main_div').find('inner_data_section').data('data1',response);
},
complete: function(jqXHR , settings){}
});
问题
作为后来添加到 div“main_div”的“inner_data_section”。 this.closest.find 无法指向 inner_data_section 这就是为什么数据也没有绑定到它。
** 我的搜索 **
我已经搜索并找到了将数据分配为 data-data1="some value" 的解决方案,我这样做了,以后也可以访问它。
但在我们的例子中,我们必须将 json 对象(复杂值)分配给内部部分 div,data-data1="some value" 仅适用于简单值。
我想我在获取 json 响应中新添加的 html 的 jquery 选择器指针时遇到了问题。
如何解决这个问题?只是提示不完整的解决方案。
【问题讨论】:
-
您希望
this采用这种成功方法。您是否已将其注销以进行验证?很可能它不是你所期望的。 api.jquery.com/jQuery.ajax 确实提供了一个context选项,你可以给它定义this在它的回调中应该是什么。
标签: javascript jquery