jQuery从另一个HTML页面获取变量值 [英] jQuery get variable value from another html page

查看:943
本文介绍了jQuery从另一个HTML页面获取变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含此内容的html页面,称为"page1.html":

I have got an html page with this content, called "page1.html":

<div>
    <div id="content">
        content
    </div>
    <script type="text/javascript">
        var x=5;
        var y=2;
    </script>
    <div id="other">Some other content</div>
</div>

在另一个html页面中,我想获取变量"x"的值(5). 这是主页:

In another html page, I'd like to get the value of the variable "x" (5). This is the main page:

<!DOCTYPE html>
<html>
<head lang="en">
    <script type="text/javascript" src="app.js"></script>
</head>
<body>
    <div id="new_content"></div>
</body>
</html>

这是app.js脚本:

And this is the app.js script:

$(function(){
    $.get('page1.html', function(result){
        var obj = $(result).find('script');
        $(this).append($('#new_content').text(obj.html()));
    });
});

结果是"var x = 5; var y = 2;".有没有办法从var x中仅获取值5?

And the result is "var x=5; var y=2;". Is there a way to get only the value 5 from the var x?

感谢您的帮助.

我忘了写这只是一个例子,page1.html中脚本的代码比所示的更为复杂. app.js中的对象"obj"是一个[object htmlscriptelement],因此我想知道是否存在可用于直接访问var x的方法/att.

I forgot to write that it's only an example, the code into the script in page1.html is more complex than the one shown. The object "obj" in app.js is an [object htmlscriptelement] so I'd like to know if a method/att exists that I can use to directly access the var x.

推荐答案

尝试执行此操作似乎有点不可思议.

This seems like a bit of a weird thing to try and do.

我会尽力回答,但是最好能有更多有关您为什么要这样做的背景信息,因为这可能是一种更好,更清洁的方法.

I'll do my best to answer but it would be good to get a bit more context around why you want to do this as it might be that there's a better, cleaner way to do it.

我对您提供的信息的建议是将值分配给DOM对象,jQuery的构建目的是遍历DOM并对其进行操作,尝试解析原始javascript以提取变量确实不是一个好主意.值.

My recommendation with the information that you've given would be to assign the values to a DOM object, jQuery is built to traverse the DOM and manipulate it, it's really not a good idea to try and parse raw javascript to extract variable values.

因此,第1页如下所示:

So, page 1 would look like this:

<div>
    <div id="content">
        content
    </div>
    <div class="myData" data-x="5" data-y="2" />
    <div id="other">Some other content</div>
</div>

然后我的jQuery看起来像这样:

Then my jQuery would look something like this:

$(function(){
    $.get('page1.html', function(result){
        var obj = $(result).find('script');
        var page1X = $(result).find('div.myData').data('x');
        var page1Y = $(result).find('div.myData').data('y');
    });
});

这只是伪代码,但希望您能理解.

This is just pseudo code, but hopefully you get the idea.

参考链接:

这篇关于jQuery从另一个HTML页面获取变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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