jquery默认上下文
我想将一个页面(带有js,css)加载到同一文档中的DIV中,加载页面中的javascript不能应用于父页面内容。是否可以在加载的页面上设置类似默认上下文的内容?请参阅下面的基本示例
I'd like to load a page (with js, css) into a DIV within the same document and javascript in loaded page mustn't apply on parent page content. Is it possible to set something like default context on the loaded page? see the basic example bellow
父页面:
<h1>normal</h1>
<span class="externalpage">data</span>
<script>
$(document).ready(function () {
$.ajax({
url: "/ajax/Index",
success: function (data) {
$(".externalpage").html(data);
}
});
})
</script>
/ ajax / Indexsubpage - 我不会改变此页面的内容。
/ajax/Index "subpage" - I'm not alowed to change content of this page.
<h1>ajax</h1>
<script>
$(document).ready(function () {
$("h1").text("xxxxxxxxxxxxx");
})
</script>
从您的评论中,您希望加载的脚本能够执行在某种部分文档上下文中,仅限于 externalpage
元素的内容(即只加载< h1>
元素必须更改,而不是< div>
之外的元素。
From your comments, you want the loaded scripts to execute in some kind of "partial" document context, limited to the contents of your externalpage
element (i.e. only the loaded <h1>
element must change, not the one outside the <div>
).
这可以实现暂时覆盖 $。find()
(不 $ .fn .find(),这不是一回事),并在上下文中替换
参数如果未指定或等于文档本身: externalpage
元素
That can be achieved by temporarily overriding $.find()
(not $.fn.find(), which is not the same thing), and substituting the externalpage
element in the context
argument if it is unspecified or equal to the document itself:
$(document).ready(function () {
$.ajax({
url: "/ajax/Index",
success: function(data) {
var $root = $(".externalpage");
var realFind = $.find;
$.find = function(query, context, extra, seed) {
return realFind.apply(this, [
query,
context && context !== document ? context : $root[0],
extra,
seed
]);
};
$root.html(data);
$.find = realFind;
}
});
})
jsFiddle提供了一个echo服务,我可以用来测试这个解决方案。您可以在此处查看结果。
jsFiddle features an echo service that I could use to test this solution. You can see the results here.