dps123456789 2012-10-10 15:10
浏览 40
已采纳

如何将php参数传递给javascript [复制]

Possible Duplicate:
pass php variable value to javascript

I have a piece of php code

function formLetterTabPage($redirect_url, $letter){
  $test = 123;
  foreach (range('A','Z') as $val) {
    if($val == $letter){
        echo '<li class="a" id="li_'.$letter.'" onclick="tab_click('.$letter.')">'.$letter.'</li>';
    }else{
        echo '<li class="b" id="li_'.$val.'" onclick="tab_click('.$letter.')">'.$val.'</li>';
    }
  }
}

and my javascript function tab_click is quite simple:

function tab_click(f){
  alert(f);
}

the key part is here:

echo '<li class="a" onclick="tab_click('.$letter.')">'.$letter.'</li>';

it cannot work out ! so I change it like this:

$test = 123;
echo '<li class="a" onclick="tab_click('.$test .')">'.$letter.'</li>';

it works perfert, and the page show me 123! I wonder why this happen? And I checked the html code, it ok:

<li class="navi_letter_leftb" id="li_A" onclick="tab_click(A)">A</li>

ok, I don't know why?

  • 写回答

2条回答 默认 最新

  • dpfps86064 2012-10-10 15:12
    关注

    You need additional quotes in your javascript for string parameters:

    echo '<li class="a" onclick="tab_click(\''.$letter.'\')">'.$letter.'</li>';
    

    In your test case $test = 123; you are passing an integer, so the quotes are not needed.

    EDIT

    Output without quotes (invalid javascript):

    <li class="a" onclick="tab_click(a)">a</li>
    

    Output with quotes:

    <li class="a" onclick="tab_click('a')">a</li>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题