首页 > 解决方案 > 通过使用jquery将php字符串传递给onclick函数来获取[object Object]

问题描述

我想提醒你好,而不是我得到 [object Object]。通过使用jquery将php字符串传递给onclick函数来获取[object Object]

<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<p id="demo"></p>

<a class="readmore" onclick="myFunction('<?php echo "hello";?>')">Readmore....</a>

<?php
call();
function call(){
?>
<script>
$(document).ready(function(){
  $(".readmore").click(function(link){
    alert(link);
  });
}); 
</script>
<?php }
?>
</body>
</html>

标签: javascriptphpjquery

解决方案


问题是您的 JavaScript 代码。您正在调用一个不存在的函数。这就是为什么它什么都不做。如果您想在 jQuery 中执行此操作,则必须定义链接。否则,link 等于 [object Object],因为 link 是由一个函数传递的,该函数在没有属性 link 的情况下调用。

固定的:

  <!DOCTYPE html>
    <html>
    <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <p id="demo"></p>
    
    <a class="readmore" onclick="show_alert('<?php echo "hello";?>')">Readmore....</a>
    
    <?php
    call();
    function call(){
    ?>
    <script>
    function show_alert(link) {
      alert(link);
    }
    </script>
    <?php }
    ?>
    </body>
    </html>

使用 Jquery:

  <!DOCTYPE html>
    <html>
    <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <p id="demo"></p>
    
    <a class="readmore" link="test">Readmore....</a>
    
    <?php
    call();
    function call(){
    ?>
    <script>
      $(".readmore").click(function(){
      link = $(".readmore").attr("link");
       alert(link);
      });
    </script>
    <?php }
    ?>
    </body>
    </html>

推荐阅读