【问题标题】:jQuery doesn't work for dynamic elements but works fine in consolejQuery 不适用于动态元素,但在控制台中可以正常工作
【发布时间】:2020-12-26 16:46:48
【问题描述】:

我正在使用在我的网站上显示来自 Instagram 的图像的插件。当我尝试为插件创建的任何元素应用 jQuery(任何 jQuery,即$('.instagram_gallery').css('display', 'none'))时,它在控制台中有效,但在代码中无效。我知道 jQuery 在加载 DOM 之前不会看到此代码。但问题是没有一个解决方案有效 - 我尝试了 $(document).ready(function() {})$(window).on('load', function(){})

你可以在这个网站上看到插件(Instagram画廊部分):10oz.ru/mlight

带有设置的文件,我试图在其中添加 jQuery:

    <?php
class shopInstafeedPlugin extends shopPlugin
{    public static function display()
    {
        $plugin = wa('shop')->getPlugin('instafeed');
        $settings = $plugin->getSettings();
        $settings_json = json_encode($plugin->getSettings());
        $root = $plugin->getPluginStaticUrl();
        $html = <<<HTML
        <div id='instafeed'></div>
        <script src="{$root}js/jquery.instagramFeed.min.js"></script> 
        <script>
             (function($){
                $(window).on('load', function(){
                    $.instagramFeed($settings_json); 
             });
             })(jQuery);   
        </script>
<style>
HTML;
        if (!$settings['styling']) {
            $html .= $settings['css'];
        }
        return $html;
    }
}

所以最后这段代码对我有用:

var settings = $settings_json;
    var callback = {callback: function (data){
       $('.instagram_gallery').hide();                
    }};
    jQuery.extend(settings, callback);
    (function($){
        $(window).on('load', function() {
            $.instagramFeed(settings);
        });
    }) 
    (jQuery);

【问题讨论】:

    标签: jquery dynamic instagram


    【解决方案1】:

    您是正确的,您需要在将新图像添加到 DOM 之后运行您的代码。从您的描述中假设您使用的是this jQuery Instagram library,那么您可以使用callback 属性来实现:

    <script src="{$root}js/jquery.instagramFeed.min.js"></script>
    <script>
      jQuery($ => {
        $.instagramFeed({
          callback: () => {
            $('.instagram_gallery').hide(); // note use of hide() instead of css()
          },
          // your other settings in this object...
        });
      });
    </script>
    

    【讨论】:

    • 谢谢,这是我用的插件。您能否帮我将 json 中的设置添加到您的构造中,它应该是什么样子? &lt;script&gt; jQuery($ =&gt; { $.instagramFeed({ callback: () =&gt; { $('.instagram_gallery').hide(); // note use of hide() instead of css() }, ($settings_json) }); }); &lt;/script&gt;
    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 2021-06-13
    相关资源
    最近更新 更多