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 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计