<script type="text/javascript">
function gr8r( form ) {
document.write( '"' + form.s1.value + '"' );
if ( form.s1.value > form.s2.value )
document.write( ' is gr8r than ' );
else
document.write( ' is not gr8r than ' );
document.write( '"' + form.s2.value + '"' );
}
</script>
<form action="" method="post">
<input type="text" name="s1" value="" />
<input type="text" name="s2" value="" />
<br />
<input type="button" value="click" onclick="gr8r(this.form)" />
</form>
我期望的结果是我点击按钮然后显示html表单后执行javascript ...但是html表单后来没有显示......
非常感谢任何帮助,谢谢!
我想要的输出是:
2 is gr8r than 1
<form action="" method="post">
<input type="text" name="s1" value="" />
<input type="text" name="s2" value="" />
<br />
<input type="button" value="click" onclick="gr8r(this.form)" />
</form>
答案 0 :(得分:1)
你想要完成什么?在表格下方或上方显示文字? Document.Write实际上会在加载期间未内联运行时覆盖文档的整个内容。因此,要执行您想要执行的操作,您需要创建一个容器来放置文本,然后将文本放在那里。例如:
<div id="message"></div>
<form action="" method="post">
<input type="text" name="s1" value="" />
<input type="text" name="s2" value="" />
<br />
<input type="button" value="click" onclick="gr8r(this.form)" />
</form>
然后javascript将是:
<script type="text/javascript">
function gr8r( form ) {
message = document.getElementById("message");
msgStr = '"' + form.s1.value + '"';
if ( form.s1.value > form.s2.value )
msgStr += ' is gr8r than ';
else
msgStr += ' is not gr8r than ';
msgStr += '"' + form.s2.value + '"';
message.innerHTML = msgStr;
}
</script>
更好的方法是使用名为JQuery(http://jquery.com)的JavaScript框架。它提供了附加事件处理程序和操作内容的简便方法。删除内联JavaScript有利于维护。
答案 1 :(得分:1)
你可以试试这个:
<script type="text/javascript">
function gr8r( form ) {
document.getElementById("output").innerHTML = document.getElementById("s1").value;
if ( document.getElementById("s1").value > document.getElementById("s2").value )
document.getElementById("output").innerHTML += ' is gr8r than ';
else
document.getElementById("output").innerHTML += ' is not gr8r than ';
document.getElementById("output").innerHTML += document.getElementById("s2").value;
}
</script>
<div id="output"></div>
<form action="" method="post">
<input type="text" id="s1" value="" />
<input type="text" id="s2" value="" />
<br />
<input type="button" value="click" onclick="gr8r(this.form)" />
</form>
div用于显示输出。表格的div和字段都由他们的id选择。
如果您想确保用户没有输入字符串,请使用此javascript:
function gr8r( form ) {
if (isFinite(document.getElementById("s1").value) && isFinite(document.getElementById("s2").value)) {
document.getElementById("output").innerHTML = document.getElementById("s1").value;
if (document.getElementById("s1").value > document.getElementById("s2").value)
document.getElementById("output").innerHTML += ' is gr8r than ';
else
document.getElementById("output").innerHTML += ' is not gr8r than ';
document.getElementById("output").innerHTML += document.getElementById("s2").value;
}
else {
document.getElementById("output").innerHTML = "Please enter only floats!";
}
}