drtppp75155 2015-07-16 05:54
浏览 46
已采纳

将字符串值作为参数传递给javascript [复制]

This question already has an answer here:

I`m trying to pass a string value to a JavaScript parameter. this is my html code

<input type="submit"  value="Edit" onclick="edit(<?php echo $key; ?> );" name="<?php echo $key; ?>" >

this is my JavaScript function

<script type="text/javascript">
function edit(id){
window.location.href="http://localhost/koko/edit-post.php?id="+id;
}
</script>

But this didn't work for me. How I solve this problem?

</div>
  • 写回答

1条回答 默认 最新

  • douyouming9180 2015-07-16 05:55
    关注

    As the type of $key is string you need to surround it in quotes. Use quotes to the parameter.

    onclick="edit('<?php echo $key; ?>');"
    //            ^                   ^
    

    Better way:

    As the name what you want in the function, you can get it by using the element.name.

    See the comments highlighted in the code below:

    HTML:

    <input type="submit" value="Edit" onclick="edit(this);" name="<?php echo $key; ?>">
    <!--                                            ^^^^ Pass the element instance to the function -->
    

    Javascript:

    <script type="text/javascript">
    function edit(el) {
        //        ^^ // Get the element instance here
        window.location.href = "http://localhost/koko/edit-post.php?id=" + el.name; // Use element.name to get the `$key` value.
        //                                                                 ^^^^^^^
    }
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型