简体   繁体   中英

JQuery .on(“click”) event not triggering

I am currently working on a "split-screen" web application. It uses selenium to retrieve the html of a webpage then sends and displays it in iframes using srcdoc. I want, when someone presses a link in the first screen, for the second screen to display a simple "Loading" while an ajax request is sent to the backend to retrieve the html of the url (as it might take a couple of seconds to load) then display the retrieved html in the second screen.

To do so, I "inject" a JQuery event code into the src code of the first screen in the backend (shown below) right before the end body tag (as the retrieved source is a string, that is easy to do). The second screen has id="oframe".

For some reason, the JQuery event wont trigger. Any ideas why?


<script>
    $("a").on("click",function(e){ 
    e.preventDefault(); 
    if(e.target.href){ 
        let link = e.target.href;
        parent.document.getElementById("oframe").srcdoc="<html><head></head><body>
                                                       <p>Loading</p></body></html>";
        $.ajax({ 
            url: "/newOrigin",
            data: {"link":link}, 
            type: "POST", 
            success: function(response) { 
                 parent.document.getElementById("oframe").srcdoc=response.site;}, 
            error: function(error) {console.log(error);} 
        });
    }});
    </script>

Note that the event works if I only have

parent.document.getElementById("oframe").srcdoc="<html><head></head><body>

or

$.ajax({ 
            url: "/newOrigin",
            data: {"link":link}, 
            type: "POST", 
            success: function(response) { 
                 parent.document.getElementById("oframe").srcdoc=response.site;}, 
            error: function(error) {console.log(error);} 
        });

inside the if statement.Together they stop the event, I know that because preventDefault() is not working (link opens in a new tab).


Example <a> tag:

<a class="gdpr-modal-link" target="_blank" ref="http://www.politifact.com/privacy/">cookies</a>

You cannot have a line break in the middle of JavaScript string.

So, put this:

parent.document.getElementById("oframe").srcdoc="<html><head></head><body>
                                               <p>Loading</p></body></html>";

all on one line:

parent.document.getElementById("oframe").srcdoc="<html><head></head><body>p>Loading</p></body></html>";

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