簡體   English   中英

如何在 PHP 標記回顯內的腳本中使用 jquery 變量?

[英]How to use the jquery variable in script inside the PHP tag echo?

我得到了這個問題

警告:使用未定義的常量 otherInput - 假定為“otherInput”(這將在 PHP 的未來版本中引發錯誤)警告:遇到非數字值

我知道報價有問題。

我正在做的是,我必須單擊名為Click me one的錨標記並在腳本中發送數據 ID。 我在腳本中獲取 id 值,但在$(".showme'+otherInput+'").show();

我正在使用 WordPress,我必須在 function.php 中使用以下代碼,所以我必須在 PHP 標簽中使用我的腳本。

這是代碼的截圖在此處輸入圖片說明

這是代碼

<!DOCTYPE html>
<html>
   <head>
      <title></title>
      <style type="text/css">
         .showme{display: none;}
      </style>
   </head>
   <body>
      <div class="clickme" data-id="1">Click me one</div>
      <div class="showme showme1">this is example</div>
      <?php
         echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
         <script type="text/javascript">
             $(".clickme").click(function(){
             var otherInput=$(this).data("id");  
               $(".showme'+otherInput+'").show();
               });.
         </script>';
         ?>
   </body>
</html>

看起來您的 php 塊中的所有內容都是 JQuery/Javascript。

問:你甚至需要 PHP 塊和“echo”來做什么?

當前的:

  <?php
     echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
     <script type="text/javascript">
         $(".clickme").click(function(){
            var otherInput=$(this).data("id");  
            $(".showme'+otherInput+'").show();
         });.
     </script>';
     ?>

建議更改:

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script type="text/javascript">
      $(".clickme").click(function(){
         var otherInput=$(this).data("id");  
         $(".showme"+otherInput).show();
      });.
  </script>'

只需遵循常規的 js 標准,如果您願意在 php 代碼中實現您的腳本:

用以下更改替換您的代碼:

            <!DOCTYPE html>
        <html>
           <head>
              <title></title>
              <style type="text/css">
                 .showme{display: none;}
              </style>
           </head>
           <body>
              <div class="clickme" data-id="1">Click me one</div>
              <div class="showme showme1">this is example</div>
              <?php
         echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
         <script type="text/javascript">
             $(".clickme").click(function(){
                var otherInput=$(this).data("id");  
                $(".showme"+otherInput).show(); 
                
                //here otherInput js variable is just used as regular js variable inside the script, so no need to extra commas to call that js variable, just use it like you do in js files, and will work fine.
             });
         </script>';
         ?>

           </body>
        </html>

暫無
暫無

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

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