【问题标题】:onClick function inside a form with submit button causes error带有提交按钮的表单内的onClick函数会导致错误
【发布时间】:2014-03-19 22:41:18
【问题描述】:

当我在 frontend.php 的表单标签内使用带有 onClick 函数的 JavaScript 按钮时,会导致错误。我需要这个简单的应用程序来完成简单的工作,但它卡在了这个位置。

我为您提供两个链接。首先是在表单标签 (frontend.php) 中,它在那里不起作用 - 添加按钮根本不会添加更多文本!第二个链接没有表单标签,它可以工作,你可以尝试提交,这会让你进入 welldone.php 页面。

1.LINK - There is a problem

2.LINK - No form tag, no problem

HTML 表单

<form action="http://www.balkanex.info/dev/frontend.php" method="post">
    Title: <br/><input type="text" name="title"><br/><br/>
    The question is: <br/><input type="text" name="ask"><br/><br/>
<br/>
    <input type="submit" name="submit" value="PROCEED"><br/>
</form>

FRONTEND.PHP 文件

<script>
am = 1;
function more(index) {
        am++;
        var textarea = document.createElement("textarea");
        textarea.name = "answer" + am;
        var div = document.createElement("div");
        div.innerHTML = textarea.outerHTML;
        document.getElementById("inner1").appendChild(div);
}
</script>

<?php
echo '<form action="welldone.php" method="post">';
$content = "";
$title = $_POST['title'];
$question = $_POST['ask'];

if($_POST['ask'] != "") {
    $answer = '<textarea name="answer1"></textarea>';
    $more = '<button type="button" name="more" onClick="more();">Add more</button>';
    $content .= '1) '.$question.'<br/>'.$answer.'<br/><div id="inner1"></div>'.$more.'<br/><br/>';
}
echo $content;
echo'<br/><input type="submit" value="CALCULATE"></form>';
?>

结果 WELLDONE.PHP 文件

<?php
echo 'WOW, WELL DONE';
?>

【问题讨论】:

  • 元素名和函数名一样,所以元素名在全局范围内覆盖了函数。

标签: javascript php html forms


【解决方案1】:

问题是,当您使用more 时,浏览器使用&lt;button name="more"&gt; 而不是function more。然后,你得到

TypeError: more is not a function

这种行为只存在于表单中,这就是为什么没有表单你的代码可以工作。

您可以通过以下方式之一修复它:

  • 更改函数名称
  • 更改按钮名称
  • 编写不显眼的 javascript,从 &lt;script&gt; 元素而不是内联 onclick 属性添加事件处理程序。

无论如何,您的代码完全无效并且处于怪癖模式。您应该验证它并修复错误。

【讨论】:

  • 感谢您的建议。你说代码无效并且处于怪癖模式是什么意思。如何验证?我是金发女郎:D
  • @user3392725 :S 我不明白,我确定我链接了validatorQuirks mode 表示您没有 doctype,因此某些浏览器(基本上是 IE)的行为不标准。
猜你喜欢
  • 2015-08-19
  • 1970-01-01
  • 1970-01-01
  • 2010-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-12
相关资源
最近更新 更多