douhuan6157 2013-05-21 11:04
浏览 89
已采纳

在onClick中使用PHP变量[关闭]

I was wondering what is wrong with this tag I am using which uses a PHP variable within an onClick event.

after looking around for other answers on this i have tried to do it but for some reason it doesnt work.

<a onclick="setCartDisplay('<?=$prodID;?>'); return false;" href="prodtest2.php?action=add&id=<?=$id;?>">

Here is the code leading up to and including the link tag that doesnt work.

$prod_query = 'SELECT * FROM *****.*****';
        $prod_details = db_query_into_array_enhanced($mysql_connection, $prod_query);                       
        $count = count($prod_details);
        for($i = 0; $i < $count; $i++) 
            {?>     
            <?  $prodID = $prod_details[$i]['catID'];
                $prodDesc = $prod_details[$i]['shortDescription'];
                $prodPrice = $prod_details[$i]['rrp'];
            ?>
             <tr>
                 <td><?=$prodID;?></td>
                 <td><?=$prodDesc;?></td>
                 <td><?=$prodPrice;?></td>
                 <td><a onclick="setCartDisplay('<?=$prodID;?>'); return false;" href="prodtest2.php?action=add&id=<?=$prodID;?>">Add To Cart</a></td>
  • 写回答

1条回答 默认 最新

  • drzil26260 2013-05-21 11:15
    关注

    A better solution is to store the id from php, as the id of the anchor element and retrieve it after using javascript.

    As of html 5 any characters are valid for an id (and as it is a product ID I am guessing there will not be duplicates, if there are simply add it as a class instead with a prefix). This way would also require you to have a class on the anchors.

    This gets around you having to set the onclick of the a tag, which in my eyes is always a bad idea as it mixes your html with javascript, and imagine if you had a 1000 of these links on your page and the function name changed, you can start to see why it becomes a better solution;

    The html;

    <a id="<?= $prodID; ?>" class="product" href="prodtest2.php?action=add&id=<?= $id; ?>">
    

    And the javascript (Jquery)

    $(".product").click(function() {
         var id = $(this).attr("id");
         setCartDisplay(id);
    });
    

    The reason your link is not working in the first place is because you are returning false from your function call which disables the default behaviour of the click event.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题