简体   繁体   English

如何在js片段完全加载后添加jQuery代码?

[英]How to add jQuery code after js snippet is fully loaded?

I'm having trouble adding click function to the button which is loaded with JS snippet, because when I try doing the function like this on document.ready我在向加载了 JS 代码片段的按钮添加点击功能时遇到问题,因为当我尝试在 document.ready 上执行这样的功能时

jQuery(document).ready(function( $ ){   
    $(".esis__heading").on('click', function(event){
      console.log('123123');
})});

it fails because the element is not loaded and visible yet.它失败是因为该元素尚未加载和可见。

I was thinking maybe timeout is a solution but I started to think it's not a perfect solution.我在想也许超时是一个解决方案,但我开始认为这不是一个完美的解决方案。 If someone has any advice on how to deal with this it would help a lot.如果有人对如何处理这个问题有任何建议,那将大有帮助。 This is the link to a page which has a snippet that loads after some time https://samsung.plutonium.rs/samsung/这是一个页面的链接,该页面具有一段在一段时间后加载的代码段https://samsung.plutonium.rs/samsung/

Thanks in advance.提前致谢。

You solve this by delegating the click to a parent element, at worst this can be the document itself您可以通过将点击委托给父元素来解决这个问题,最坏的情况是这可能是document本身

$(document).ready(function( $ ){   
    $(document).on('click', ".esis__heading", function(event){
      console.log('123123');
    });
});

You can defer the load of the script using the defer attribute您可以使用 defer 属性延迟脚本的加载

Defer documentation (w3schools.com)推迟文档 (w3schools.com)

The only downside is that it works only on external scripts (script tags with src attribute).唯一的缺点是它只适用于外部脚本(带有 src 属性的脚本标签)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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