如何访问通过jQuery load()发送给div的URL参数 [英] How to access URL parameters sent to div via jQuery load()

查看:594
本文介绍了如何访问通过jQuery load()发送给div的URL参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery load()将部分页面加载到div中.我想像这样将url参数传递给部分页面

I am using jQuery load() to load a partial page into a div. I want to pass url parameters to the partial page like so

<div id='partial'></div>
<script>
$('#partial').load('child_page.html?key=1');
</script>

如何从子页面内部访问这些参数?我在子页面中尝试了以下操作,但问题是window.location不是给我child_page.html?key = 1而是给了我根页面url.

How do I access these parameters from inside the child page? I tried the following in the child page, but the issue is that the window.location is not giving me child_page.html?key=1 but is giving me the root page url.

<script>
var url = window.location;
//code to parse the url to extract the parameters goes here
</script>

推荐答案

子页面"不可能具有自己的DOM和脚本上下文,因为它只是作为字符串(通过AJAX)检索并插入的进入父页面.因此,它没有自己的window.location.一切都添加到父页面的DOM中,并且脚本在父页面的上下文中执行.

It is not possible for the "child page" to have its own DOM and scripting context, because it was simply retrieved as a string (via AJAX) and inserted into the parent page. Therefore it does not have its own window.location. Everything is added to the DOM of the parent page, and scripts are executed in the context of the parent page.

如果要在父页面和加载有load的新脚本之间共享变量,可以将变量附加到window,然后在子页面"的脚本中访问它.

If you want to share variables between your parent page and the new script loaded with load, you can attach the variable to window and then access it in the script of the "child page".

例如:

// parent page
window.sharedVariable = "Hello World!";
$('#partial').load(url);

// child page
var v = window.sharedVariable;

工作演示( 更新:

这是使用数据属性共享变量来支持多个部分的一种替代方法.

Here is an alternate method to support multiple partials, using data attributes to share the variables.

// parent page
$('#partial_1').load(url).data("param", "111");
$('#partial_2').load(url).data("param", "222");
$('#partial_3').load(url).data("param", "333");

// child page
var scriptTag = document.scripts[document.scripts.length - 1];
var parentTag = scriptTag.parentNode;
var param = $(parentTag).data("param");

基本上,我们在分部的div中设置要共享的数据.然后在子页面"中,找到当前正在运行的脚本标记,然后父标记将是其中包含数据的div.

Basically, we set the data we want to share in the partial's div. And then in the "child page", we find the current running script tag, then the parent tag would be the div that has the data in it.

工作演示( 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆