如何从PHP打印按钮调用JavaScript函数

How to call JavaScript function from a PHP printed button

本文关键字:调用 JavaScript 函数 按钮 打印 PHP      更新时间:2023-09-26

好奇怪的问题。如果有人有更好的标题,请继续编辑;我想不出还能怎么称呼它。我正在使用echo从PHP打印按钮。按钮的目的是通过调用JavaScript函数来显示表单,该函数使用document.getElementById()将表单标记的样式属性更改为可见,以便表单对用户可见。我所遇到的问题是,回声字符串必须有引号周围,onclick事件必须有引号周围,参数传递给JavaScript函数必须有引号周围。我尝试用反斜杠转义参数的引号,但这不起作用。有人能帮我吗?

下面是我的代码:
echo "<input type = 'button' onclick = 'showform(''psswdform'')' value = 'Change password'>";//this shows the form and needs quotes

JavaScript函数:

function showform(id)
{
document.getElementById(id).style.visibility = "visible";
}

这对我来说很好吗?(工作)

<?php
echo "<input type = 'button' onclick = 'showform('"psswdform'")' value = 'Change password'>";//this shows the form and needs quotes

生成:

<input type = 'button' onclick = 'showform("psswdform")' value = 'Change password'>

尝试使用单引号和双引号的组合来连接字符串,像这样:

echo '<input type="button" onclick="showform(' . "'psswdform'" . ')" value="Change password">';

试试这个:

echo "<input type = 'button' onclick = 'showform('psswdform')' value = 'Change password'>";

另外,你可以试试jQuery,一个超级流行的JS库,它使生活更容易。

我将创建以下CSS类:

.hide {
   display:none;
}

那么我将添加以下jQuery:

$("#show-password-reset").click(function(event){
 event.preventDefault();
 $("#passwdform").show();
});

最后包括show按钮:

<input id="show-password-reset" type = 'button' value = 'Change password'>

确保在passwdform元素上使用class="hide",以便在页面加载时隐藏它。

Inside PHP '已经是一个转义字符。如果你想输出"'",你需要回显"''"。