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 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器