简体   繁体   中英

Script that works in the browser console but not when in the code

I have a very simple piece of javascript code that just should work and it only works when I run it in the browser console:

<script>
    $(".hopscotch-close").click(function () {
        alert("Hi");
        Cookies.set("tourState", "closed")
    })
</script>

Because it runs in the console I know that: 1) the ".hopscotch-close" is OK; 2) there are no errors in the code that could prevent it from running;

Also: 1) because is a "click" event I know that I haven't got a problem with the DOM being ready (and I can put everywhere - but in this case in at the bottom of the <body> ; 2) I know I don't have an issue because of using the same name for a class than something else that exist; 3) The behavior is the same in Safari and Firefox, so its not a Browser issue.

I know this is tough without the full code, but if someone has experienced this maybe has na idea about what could be the problem.

From your comments I sense that the element is getting appended dynamically so instead of

$(".hopscotch-close").on('click',

you need to make use of event-delegation as

$(document).on('click','.hopscotch-close',function(){

That will do the trick.

If you are appending .hopscotch-close to any already existing static element then instead of $(document).on('click' you can use $('#yourStaticElementId').on('click','.hopscotch-close',function(){ which improves site performance.

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