How to pass text from one page to another by clicking on div using JQuery/JavaScript

前端 未结 2 514
小蘑菇
小蘑菇 2021-01-15 23:29

I\'m making a school project and i am stuck here for almost a week. what i am trying to get is... I have 2 pages PAGE 1 have more than five divs with different titles. I wan

相关标签:
2条回答
  • 2021-01-16 00:02

    If your pages are hosted by some sort of webserver you can use websockets to communicate/share data.

    If your pages are opened on the same machine/browser without any server i would recommend using the browsers session- or localstorage objects. To set a value use:

    sessionStorage.myValue = 'value'
    

    To get a value use:

    var val = sessionStorage.myValue
    

    Take a look here.

    0 讨论(0)
  • 2021-01-16 00:16

    https://www.w3schools.com/html/html5_webstorage.asp

    Use localStorage or sessionStorage:

    $('div').on('click', function() {
        localStorage.text = $(this).find('a').val(); //or sessionStorage.text
    });
    

    and

    $('.result-show-here').html(localStorage.text);//or sessionStorage.text
    

    First create a page handler on your script using jQuery:

    var pg
    switch (pg) {
            case 'page1':
                //the code for page1
                break;
            case 'page2':
                //the code for page2
                break;
        }
    

    In your case:

    for page1: on your HTML-Page:

    <script>pg = 'page1';<script>
    

    and in your script:

    //the code for page1
    $('div').on('click', function() {
        localStorage.text = $(this).find('a').val();
    });
    

    for page2:

    on your HTML-Page:

    <script>pg = 'page2';<script>
    

    and in your script:

    //the code for page2
    $('.result-show-here').html(localStorage.text);
    

    Based on your case.

    I prefer to add a class on the a-tag like <a class="city">London</a> and get the right value:

    //the code for page1
        $('div').on('click', function() {
            localStorage.text = $(this).find('.city').val();
        });
    
    0 讨论(0)
提交回复
热议问题