将字符串值作为参数传递给javascript

passing string value as a parameter to javascript

本文关键字:参数传递 javascript 字符串      更新时间:2023-09-26

我试图将字符串值传递给JavaScript参数。这是我的HTML代码

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

这是我的JavaScript函数

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

但这对我不起作用。如何解决这个问题?

由于$key的类型是string,您需要将其用引号括起来。在参数后面加上引号

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

更好的办法:

作为函数中需要的name,可以通过element.name得到。

请参阅下面代码中突出显示的注释:

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>