简体   繁体   中英

JQuery hover selector works in Chrome dev tools but not in code

I want to set a hover event for elements matching a selector. I have written the following line of code to do this.

$(".myclass > [myattr=50]").hover(()=>console.log("d"))

If I open up Chrome dev tools and run this line of code, and then hover over the appropriate element on the page, the console logs the letter "d". However, if I run this line of code in javascript then the hover selector does not work. What might be causing this issue? How can I debug it?

Note: I am using Jquery as an escape hatch in an application that uses react very heavily. I understand that this is not standard. For my specific use case, I really need Jquery.

As @epascarello said it could not find element or the element could be recreated after your code, basically its all about timing if you dont have an event or anything to wait before your code, you can use setTimeout function to delay your code execution. Start with small timeout and try to increase until it works.

setTimeout(function(){ $(".myclass > [myattr=50]").hover(()=>console.log("d")); }, 500);

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