gpt4 book ai didi

javascript - 为什么我的 JavaScript 调用在将文档类型切换为 HTML5 后无法在表单中工作

转载 作者:可可西里 更新时间:2023-11-01 12:59:37 25 4
gpt4 key购买 nike

我有一个表单,它使用 JavaScript 来根据用户的选择显示其他字段。该代码使用 XHTML 1.1 文档类型(不是我的选择......蹩脚的学校项目指南)工作正常,但在切换到 HTML5 文档类型后没有任何效果。让任何 JavaScript 在表单内部工作的唯一方法是将它直接放在 onchange="" 设置中;仅仅在那里添加函数调用是行不通的。我也尝试过事件监听器,但这也不起作用。

为简单起见,我只显示其中一个动态字段的代码:

<!DOCTYPE html>
<html><head>
<?php include "phpself.php"; ?>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

<script type="text/javascript">
document.getElementById("visitor").addEventListener("change", function(ev) {
Visitor();
});

function Visitor() {
var visitor = document.getElementById("visitor").value;

if (visitor=="Other") {
var othertext="<label>What would you consider yourself?</label><br/><input type="text" name="other_visitor" id="other_visitor"/>";
document.getElementById("vother").innerHTML=(othertext);
}
}
</script>
</head><body>

<form action=\"".getPHPSelf()."\" enctype="text/plain" method="post" onsubmit="return FormValid();" >

<fieldset style="width=50%;">
<legend>Comments</legend>
<label>I am a:</label>
<select name="visitor" id="visitor" onchange="Visitor();">
<option value="" disabled selected style="display:none;">select...</option>
<option value="Friend">Friend</option>
<option value="Client">Client</option>
<option value="Other">Other</option>
</select>
<br/><br/><div id="vother"></div>

<input type="submit" value="Submit"/><input type="reset" value="Reset"/>
</fieldset>
</form>
</body></html>

我知道其他人也问过类似的问题,但我找到的答案都不适合我。

最佳答案

我验证了您代码中的一些问题:

  1. 此行无效(语法错误):

    var othertext="<label>What would you consider yourself?</label><br/><input type="text" name="other_visitor" id="other_visitor"/>";

    您应该转义双引号,或将它们替换为单引号

    这会起作用:

    var othertext = "<label>What would you consider yourself?</label><br/><input type=text name='other_visitor' id='other_visitor' />";
  2. 去掉内联 onchange="Visitor();粘合剂或 document.getElementById("visitor").addEventListener .您应该选择其中一种方法。

  3. 移动您的 <script>标记到你 body 的底部(就在 </body> 之前)。或者将您的代码包装到 DOMContentLoaded 中事件(IE9+)。

  4. (可选)。 (othertext) 两边不需要括号这里:

    document.getElementById("vother").innerHTML = (othertext);

工作代码:https://jsfiddle.net/mrlew/txk11m6c/

关于javascript - 为什么我的 JavaScript 调用在将文档类型切换为 HTML5 后无法在表单中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42127502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com