jQuery get variable value from another html page

僤鯓⒐⒋嵵緔 提交于 2019-12-07 03:41:32

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:

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

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:

Or you can simply use localStorage in this way:

page1.html:

localStorage.setItem("x", "value"); //setter

page2.html:

var x = localStorage.getItem("x"); //getter

you could try to comment the vat y=... line before pasting the code like:

$(function(){
    $.get('page1.html', function(result){
        var obj = $(result).find('script');
        $(this).append($('#new_content').text(obj.html().replace('var y','//var y')));
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!