简体   繁体   中英

Keypress Function for two pages

I have a page which when a link is clicked, I use the ajax call to load up its content in a given div . Now my problem is this, In pages of link-1 and link-2 I have this code in each

<!-- THIS IS FOR THE FIRST LINK-->
$(document).keyup(function(e) {
    x = document.getElementById("show_photo<?php echo $id; ?>");
    y = document.getElementById("full_photo<?php echo $id; ?>");
    if(e.keyCode == 27){
        if(y.style.display == "block"){
            $("#full_photo<?php echo $id; ?>").css('display', 'none');
        } else if(x.style.display !== "block"){
            $("#all_photo<?php echo $id; ?>").css('display', 'none');
        }
    }
});

<!-- THIS IS FOR THE SECOND LINK-->
$(document).keyup(function(e) {
    x = document.getElementById("show_photo");
    y = document.getElementById("full_photo");
    if(e.keyCode == 27){
        if(y.style.display == "block"){
            $("#full_photo").css('display', 'none');
        } else if(x.style.display !== "block"){
            $("#all_photo").css('display', 'none');
        }
    }
});

The id s are different because page-1 runs in a DB query loop. Now If link-1 is clicked and the page loads up, the code functions normal but if link-2 is clicked an its page loads up, the code doesn't function again. It says Cannot read property 'style' of null in my console.log so I found out that when I load up link-1 the code is executed and when I load up link-2 even though the link-1 page isn't visible anymore the code still runs in the page. So when I click the ESC key it can't find the id s from the page-1 so I give the error in the console.log . Please is there any way I can run both codes in the two different pages without both of them colliding with each other?

Try like this
--------------
code
------
    <!-- THIS IS FOR THE SECOND LINK-->
    $(document).keyup(function(e) {
        x = document.getElementById("show_photo");
        y = document.getElementById("full_photo");
        if(e.keyCode == 27){
            if(x){
                if(x.style.display !== "block"){
                    $("#all_photo").css('display', 'none');
                }
            }
            if(y){
                if(y.style.display == "block"){
                    $("#full_photo").css('display', 'none');
                }
            }
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM