You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击按钮时PHP变量传递至JavaScript出现undefined问题求助

问题原因及解决方法

核心问题有两个:

  • JS选择器无法匹配目标元素:你用$('.create-pdf')绑定点击事件,但PHP生成的<a>标签根本没添加create-pdf类,导致事件要么没绑定到正确按钮,要么误绑定到其他无关元素。
  • 缺少data-id属性:你用$(this).data("id")获取值,但PHP生成的<a>标签没有data-id属性——data()方法专门读取元素的data-*属性,自然返回undefined,哪怕href里带了id参数也没用。

修正后的代码:

PHP代码:

add_filter( 'page_row_actions', 'create_pdf_row_actions', 10, 2 );
function create_pdf_row_actions( $actions, WP_Post $post ) {
    if ( $post->post_type != 'item' ) {
        return $actions;
    }

    $actions['create-pdf'] = "<a href='#' class='create-pdf' data-id='{$post->ID}'>Create PDF {$post->ID}</a>";
    return $actions;
}

JavaScript代码:

jQuery(document).ready(function($){
    $('.create-pdf').on('click', function (e) {
        // 阻止默认跳转行为
        e.preventDefault();
        alert("button " + $(this).data("id"));
    }); 
});

补充说明:

如果不想用data-id,也可以从href参数里提取id,但这种方式不如data-*属性直观可靠。示例代码如下:

jQuery(document).ready(function($){
    $('.create-pdf').on('click', function (e) {
        e.preventDefault();
        const urlParams = new URLSearchParams($(this).attr('href').split('?')[1]);
        const id = urlParams.get('id');
        alert("button " + id);
    }); 
});

内容的提问来源于stack exchange,提问作者Martha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:15:33