jquery获取script标签 变量值_jQuery从另一个HTML页面获取变量值

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

content

var x=5;

var y=2;

Some other content

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

This is the main page:

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()));

});

});

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

Thanks for the help.

EDIT: 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.

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.

So, page 1 would look like this:

content

Some other content

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.

Reference links:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值