jQuery ajax混合html/js
\nmyAjaxResponse.html:\n
问题的出现原因:在使用jQuery的ajax方法加载HTML或JS内容时,如果这些内容包含
代码示例二:
$(function(){ $.ajax({ url: '/myAjaxResponse.html', context: $('#mydiv'), success: function(resp) { $("#mydiv").html(resp); } }); });
代码示例三:
$(function(){ $('#mydiv').each(function(){ $.ajax({ url: '/myAjaxResponse.html', context: $(this), success: function(resp) { $("#mydiv").html(resp); } }); }) });
以上是解决这个问题的两种方法。第一种方法使用了全局变量,在XHR加载之前将需要的上下文保存到全局变量中,然后在回调函数中使用这个全局变量。第二种方法使用了context参数,直接将需要的上下文作为参数传递给ajax方法。两种方法都可以解决上下文丢失的问题。