简体   繁体   中英

Re-rendering jQuery function

So, I have following jquery function:

        jQuery('.button').click(function(e) {               
            if(!isMobile) {
                jQuery('.button').featherlight({                        
                });                                         
            }   
        })

This creates an lightbox at the bottom of <body> like below:

Before lightbox is opened:

<body>
    <button> Show lightbox</button>
    <script src="https://...jquery.min.js"></script>
    <script src="https://...custom_js.js"></script>
</body> 

After lightbox is opened:

<body>
    <button> Show lightbox</button>
    <script src="https://...jquery.min.js"></script>
    <script src="https://...custom_js.js"></script>
    <div class="lightbox">Lightbox content</div>
</body> 

Problem is that none of the jQuery function inside of this lightbox works as it was created after the page was loaded.

How do I "re-render" a js file after the lightbox is created?

Thanks!

Here is an example:

jQuery('#tags').keyup(function(e){
    console.log(e);                    
     if(e.which == 188) {
        var tag  = ...;
        var data = '<button>tag</button>';
        tags.push(tag);
        jQuery('.tags ul').append(data);
        jQuery(this).val('');
                }               
        });

Here, a tag input will be "appended" or added to a div class="tags". However inside of the lightbox, this function is not executed at all.

Re-rendering a JS file is not how javascript is supposed to work.

What I recommend you to do is to run the a function in the afterContent callback.

As you can see in the featherlight documentation, there is a plenty of callbacks that can help you with this.

Example:

 jQuery('.button').click(function(e) {               
        if(!isMobile) {
            jQuery('.button').featherlight({

                afterContent: function () {
                    // Do your code here
                    // The lightbox content will be ready
                }

            });                                         
        }   
    })

The proble here is that the light ox is dynamically added.

If you need any triggers to work inside or on that lightbox element you will need to use:

$(document).on('click', '.lightbox .button', function(){
    ...
});

Note that you do not want this code inside that lightbox, but inside your regular js file. Simply because we do not like inline js, and second you can trigger every dynamic content on the fly with above code.

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