簡體   English   中英

單擊按鈕時將變量從 php 傳遞到 javascript

[英]Passing a variable from php to javascript on button click

您好我正在嘗試將按鈕單擊時的變量從 php function 傳遞到 javascript。output 由於某種原因未定義,但在 php function 變量確實包含數據。 知道為什么會這樣嗎?

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='#?id=".$post->ID."'  >Create PDF</a>";
    $actions['create-pdf'] = "<a href='#?id=".$post->ID."'  >Create PDF".$post->ID."</a>";
    return $actions;
}

Javascript:

  jQuery(document).ready(function($){
    $('.create-pdf').on('click', function () {
        alert("button"+ $(this).data("id"));
    }); 
  });
    

從這段代碼假設,你可以嘗試:

使用<?php?>標簽在 jQuery 內調用 PHP function。 由於$actions['create-pdf']在數組中,使用print_r到 output 變量,或者如果你有多個鍵值對,則使用foreach loop

jQuery 的.data()訪問元素的dataset ,但鏈接中的id似乎位於href屬性的 URL 片段中。

你有兩個選擇...

  1. 將適當的data-id屬性添加到您的鏈接

    $actions['create-pdf'] = sprintf( '<a href="#?id=%1$s" data-id="%1$s">Create PDF%1$s</a>', htmlspecialchars($post->ID) );
     $(".create-pdf").on("click", "a[data-id]", function(e) { e.preventDefault(); alert(`button${$(this).data("id")}`); });
  2. 或者,從 URL 片段中的參數中提取id

     $(".create-pdf").on("click", "a[href]", function(e) { e.preventDefault(); const url = new URL(this.href); const params = new URLSearchParams(url.hash.slice(1)); alert(`button${params.get("id")}`); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM