doutang1873
doutang1873
2013-04-25 09:49

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

已采纳

What a weird question. If anyone has a better title for this, please go ahead and edit it; I can't think of what else to call it. I am printing a button from PHP using echo. The purpose of a button is to show a form by calling a JavaScript function that uses document.getElementById() to change the style attribute of the form tag to visible so the form is visible to the user. The problem I'm having is that the echoed string has to have quotes around it, the onclick event has to have quotes around it, and the parameter passed to the JavaScript function has to have quotes around it. I tried escpaing the quotes for the parameter with backslashes but that didn't work. Can anyone help me?

Here is my code:

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

JavaScript function:

function showform(id)
{
document.getElementById(id).style.visibility = "visible";
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • dongmei8209 dongmei8209 8年前

    This works fine for me? (working example)

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

    Generates:

    <input type = 'button' onclick = 'showform("psswdform")' value = 'Change password'>
    
    点赞 评论 复制链接分享
  • dongruyan4948 dongruyan4948 8年前

    Try this:

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

    Additionally, you could try jQuery, a super popular JS Library that makes life easier.

    I would make the following CSS class.

    .hide {
       display:none;
    }
    

    Than I would add the following jQuery:

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

    And finally include your show button:

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

    Make sure to use class="hide" on the passwdform element so its hidden when page loads.

    点赞 评论 复制链接分享
  • dp19001 dp19001 8年前

    Try concatenating the string using a combination of single and double quotes like this:

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

    点赞 评论 复制链接分享
  • douyan1927 douyan1927 8年前

    Inside PHP \ is already an escape character. If you want to output "\" you need to echo "\\".

    点赞 评论 复制链接分享