简体   繁体   English

通过 Ajax (Wordpress) 加载内容后让 javascript 工作

[英]Getting javascript to work after loading content via Ajax (Wordpress)

I'm having some problems with loading content via Ajax.我在通过 Ajax 加载内容时遇到了一些问题。 I can't get the Woocommerce javascript to work when I am loading a product via Ajax.当我通过 Ajax 加载产品时,我无法让 Woocommerce javascript 工作。

The content is loaded like this:内容是这样加载的:

App.js应用程序.js

$.post( settings.ajaxurl, data, function( response ) {
        $button.prop("disabled",false);
        if(true === response.success) {
            $('.sidebar').html(response.data);
        }  else {
            $contentWrapper.find('.response').html(response.data.general).show();
        }
    } );

And the backend returns a template part when the request was successful.当请求成功时,后端会返回一个模板部分。

Ajax.php Ajax.php

ob_start();
    if( get_user_meta( $user->ID, 'my_custom_field', true ) == 1 ) {
        get_template_part( 'template-parts/book' );
    } else {
        get_template_part( 'template-parts/additional-information' );
    }
    $response = ob_get_clean();
    wp_send_json_success( $response );

Inside the template part "book" is a single bookable product (via Woocommerce Bookings) which requires some javascript to work for selecting time/date etc. When this template part is loaded via Ajax the javascript is not working, and I can therefore not book the product. Inside the template part "book" is a single bookable product (via Woocommerce Bookings) which requires some javascript to work for selecting time/date etc. When this template part is loaded via Ajax the javascript is not working, and I can therefore not book产品。

However if I refresh the page, the bookable product will be loaded instantly without Ajax, and now everything works perfectly.但是,如果我刷新页面,可预订的产品将在没有 Ajax 的情况下立即加载,现在一切正常。

The javascript is included globally in the header of the page and is always present. javascript 全局包含在页面的 header 中,并且始终存在。 But when the new content is loaded via Ajax, I guess I need to manually fire any document.ready functions that is needed for the booking form to work.但是当通过 Ajax 加载新内容时,我想我需要手动触发预订表单工作所需的任何 document.ready 函数。

I just cant wrap my head around how I should do this, so any help is very appreciated.我只是不知道该怎么做,所以非常感谢任何帮助。

I guess you should use your jquery events dynamically because you DOM was changed.我想您应该动态使用您的 jquery 事件,因为您的 DOM 已更改。

Try to use:尝试使用:

$(document).on( eventName, selector, function(){} );

instead of:代替:

$(selector).on( eventName, function(){} );

and etc...等等...

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

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