简体   繁体   中英

JavaScript stops working after I load another page

I am new to JavaScript and trying to see why my on event listeners are not working. I have found similar posts on stackoverflow however the solutions are not working for me.

var search = function( event ) {
    alert("bobo")
   $.get("http://localhost:3000/search", {"search" : $("#Search-Bar").val()}, function(data, status){
        if(status == "success")
           $(".centering.text-center").html(data)
    })
}

var attachListeners = function(){
    $("#Search").on("click", search)
    $("#SearchIcon").click( () => search() )
    $("#Search-Bar").keypress( event => (event.KeyCode == 13 || event.which == 13) ? search() : undefined )
}

$(document).ready( function(){ 
    attachListeners()
})

My website is not a single page application. I have attached the listeners to my navigation search bar where I load a different view through the nav links and my server(ruby back end) uploads a new html page.

On the first load I have noticed that document ready gets called and everything else works. The on and click. After I use my navigation and load a different html page my events disappear. In my html views my searchbar, searchicon, and a search text have consistent id 's through out. I have tried using window.load() and putting an onload attribute for my body <body onload=attachListeners()> but neither worked(perhaps I didn't use them properly). I also noticed that when I render the next html views my docment.ready does not get called. However, if I forcefully refresh the page with an F5 the listeners are active again for that one html page. What am I missing here that I don't understand?

It looks like you might be using Turbolinks , from the Readme for the project:

When you follow a link, Turbolinks automatically fetches the page, swaps in its <body>, and merges its <head>, all without incurring the cost of a full page load.

Since this library makes it so the page ever only loads once, normal javascript window.onload , DOMContentLoaded , and jQuery ready events don't function after the initial page load and you have to use

document.addEventListener("turbolinks:load", function() {

instead of those. If you're new to turbo links, I suggest reading through that README to see what it's all about.

I've never understood why the Rails team would put something like this in rails and enable it by default, and in every single project I've made since they made that change the first thing I do is uninstall it, and when I forgot to do so, I spend several hours later in the project wondering why my javascript is broken.

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