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

使用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条)

相关推荐 更多相似问题