duandu6497 2014-12-02 21:08
浏览 599
已采纳

使用HTML onClick将PHP变量作为参数传递

I looked through many similar examples, but I could not make this work.

So, I have this:

echo('<td colspan="3" style="background-color:#005673; text-align:right; padding: 4px 0px;">
      <button class="btnTrack" onClick="trackIt(' . $name . ')" >Track It!</button></td>');

That code is inside a for, so the variable $name will be different depending where I am at.

I am not trying to make things complicates, so first, I am just trying to pass that parameter to the function trackIt (I actually need to pass 2 of them.)

Then, I have a simple script (just to see if it will work):

<script>
//After you click on Track It

function trackIt(param) 
{
   alert("Hi!");
   alert(param);
}

</script>

However, it does not work.

If my onClick function is just onClick="trackIt()", then it works fine and I can alert "Hi!" by removing the parameter.

Thanks for the help! =]

  • 写回答

4条回答 默认 最新

  • dongxing2692 2014-12-02 21:10
    关注

    Try this..

    echo('<td colspan="3" style="background-color:#005673; text-align:right; padding: 4px 0px;">
      <button class="btnTrack" onclick="trackIt(\'' . $name . '\')" >Track It!</button></td>');
    

    Note: you have to use your way if the input parameter is a numeric value..


    You are printing HTML as,

    <td colspan="3" style="background-color:#005673; text-align:right; padding: 4px 0px;">
    <button class="btnTrack" onclick="trackIt(test)" >Track It!</button></td>
    

    But because the function trackIt needs a string as the input parameter, you have to print this..

    <td colspan="3" style="background-color:#005673; text-align:right; padding: 4px 0px;">
    <button class="btnTrack" onclick="trackIt('test')" >Track It!</button></td>
    

    As you are using ' as boundaries to define strings in PHP, you have to escape it using \' in order to make ' character part of the string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决