php - 重力形式 - 获取当前页码

标签 php javascript wordpress

我有一个多页表单。

我想在此表单的最后一页上执行一些自定义 JavaScript。理论上,我所要做的就是检索当前页码并编写条件。

很简单,对吧?显然不是。

我原来的解决方法是这样的:

if ($('gform_page').last().css('display') !== 'none') {
    // perform custom scripts now that the last
    // Gravity Form page is being shown
}

但是 $('...').css('display')every 元素上返回 undefined 我试过这个在表格内。每次用户点击“下一步”按钮时,都会触发自定义脚本。没有雪茄。

然后,经过审核the Gravity Forms documentation ,我发现了两个看起来很有用的事件:gform_post_rendergform_page_loaded

但是,文档没有提供有关如何访问参数的说明。

jQuery(document).bind('gform_page_loaded', function(event, form_id, current_page){
    console.log(current_page);
    // returns nothing when loaded in the footer
    // returns [Object, object] when placed in an HTML field in the form
});

除了没有正确的代码外,我还怀疑我没有将代码放在正确的位置,因为我在 functions.php 和 header.php ( as the documentation suggests) 中也毫无结果地尝试了以下内容:

<?php
function enqueue_custom_script($form, $is_ajax){
    if ($is_ajax) :
        echo '<script>console.log(current_page);</script>';
    endif;
}
add_action("gform_enqueue_scripts", "enqueue_custom_script", 10, 2);
?>

问题:

我需要什么代码来检索当前页码,更重要的是,我该把代码放在哪里?

最佳答案

我明白了。

函数rgpost显然,对于访问当前页码至关重要。经过我自己的一些摸索之后,我能够让以下代码在 functions.php 和 header.php 中的 wp_head() 函数之前工作。

function run_script_on_last_page($form) {
    if (!is_admin()) {
        $current_page = rgpost('gform_source_page_number_' . $form['id']) ? rgpost('gform_source_page_number_' . $form['id']) : 1;
        if ($current_page == 10) {
            wp_enqueue_script('custom_script', get_template_directory_uri() . '/js/custom_script.js', array('jquery'), null, true);
        }
    }
}
add_action('gform_enqueue_scripts_63', 'run_script_on_last_page');

如果您要复制/粘贴上面的代码,请确保:

  • 10替换成你要查看的页面
  • 确保您在 wp_enqueue_script 中的参数正确
  • 63 替换为您的表单 ID

我发现一些有用的资源:

关于php - 重力形式 - 获取当前页码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15144311/

相关文章:

javascript - 从 Facebook 获取点赞

javascript - 将带点的字符串转换为用于访问 javascript 中的嵌套对象的指令

php - 如何检查是否存在相同的列值?

php - 服务器调用的 PHP 脚本是否异步运行?

javascript - 选择单选按钮后重定向到特定页面

css - 手机上的奇怪堆栈

wordpress - 如何从 Woocommerce Plugin 获得评分的_comment_meta()?

PHP/MySQL 多列排序

javascript - 表单提交错误后记住 Selectbox 值

javascript - 在此 WP 模板上通过 MYSQL 数据库上传数百个配置文件?