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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失