4
在我的WooCommerce商店模板中,我使用Ajax在archive-product.php頁面中動態加載單產品內容。這部分工作。 但是,選擇產品變體的JavaScript缺失,所以我試圖在成功的ajax請求後將腳本添加到html。 我可以加載腳本,但我仍然無法選擇產品變體。沒有事件被觸發。好像我失去了一些東西......變體Javascript not work when single_product_content is loaded via Ajax(WooCommerce)
我的javascript:
jQuery('.project-preview').on('click',function(){
var theId = $(this).attr('data-project-id');
var div = $('#product-container');
$.ajax({
type: "POST",
url: singleprojectajax.ajaxurl,
data : {action : 'load_single_product_content', post_id: theId },
success: function(data){
div.html(data);
loadVariationScript();
},
error : function() {
}
});
});
function loadVariationScript() {
jQuery.getScript("../wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.min.js");
jQuery.getScript("../wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.js");
}
在functions.php的
add_action('wp_enqueue_scripts', 'child_add_scripts');
function child_add_scripts(){
wp_register_script('pa_script', get_stylesheet_directory_uri() . '/main.js', array('jquery'), true);
wp_localize_script('pa_script', 'singleprojectajax', array('ajaxurl' => admin_url('admin-ajax.php')));
wp_enqueue_script('pa_script');
}
function load_single_product_content() {
$post_id = intval(isset($_POST['post_id']) ? $_POST['post_id'] : 0);
if ($post_id > 0) {
$the_query = new WP_query(array('p' => $post_id, 'post_type' => 'product'));
if ($the_query->have_posts()) {
while ($the_query->have_posts()) : $the_query->the_post();
wc_get_template_part('content', 'single-product');
endwhile;
} else {
echo "There were no products found";
}
}
wp_die();
}
add_action('wp_ajax_load_single_product_content', 'load_single_product_content');
add_action('wp_ajax_nopriv_load_single_product_content', 'load_single_product_content');
的WooCommerce腳本 「添加到購物車-variations.js」: https://searchcode.com/codesearch/view/95139130/