javascript函数没有被调用/不能从html表单工作

时间:2013-08-13 19:57:42

标签: javascript html forms function

这是我的整个html页面

<html>
<head>
<title> text conversion</title>
<script type="text/javascript">
function testResults(form)
{

var str = form.stringn.value;

str.split(" ");
document.write("testing1");
var length = str.length;
var newn = "";

for(var i = 0; i<length; i++)
{
    if(str[i].charAt(str[i].length - 1) != ".")
    {
        str[i] = str[i] + ".";
    }
    str[i] = str[i] + " ";
    str[i].charAt(0) = str[i].charAt(0).toUpperCase();
    newn = newn + str[i];

}
document.write(newn);
document.write("testing");
}


</script>
</head>

<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>


</html>

正确显示html,但该按钮不会产生任何操作。我甚至在javascript中的循环下面尝试了document.write(“testing”),这没有任何效果,这让我觉得该函数根本没有被调用。该函数的思想是格式化输入字符串以大写每个单词的第一个字母,并在每个单词后面加上一个句点。

这是我第一次尝试使用javascript,所以我可能做错了什么应该是显而易见的?

最终解决方案:

<html>
<head>
<title> text conversion</title>
<script type="text/javascript">
function testResults(form)
{

var str = form.stringn.value;

var strn = str.split(" ");

var length = strn.length;
var newn = "";

for(var i = 0; i<length; i++)
{

    if(strn[i].charAt(strn[i].length - 1) != ".")
    {
        strn[i] = strn[i] + ".";
    }
    strn[i] = strn[i].charAt(0).toUpperCase() + strn[i].slice(1);

    strn[i] = strn[i] + " ";
    newn = newn + strn[i];


}
document.write(newn);

}


</script>
</head>

<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>


</html>

2 个答案:

答案 0 :(得分:5)

这应该有效。另外,回应之前关于使用new作为变量的注释。

<html>
<head>
<title> text conversion</title>
<script language="JavaScript">

function testResults(form)
{
    var str = form.stringn.value;
    var newString = "";
    var strList = str.split(" ");
    for(var i = 0; i < strList.length; i++){
        newWord = strList[i].charAt(0).toUpperCase() + strList[i].slice(1) + ".";       
        newString += newWord + " ";
    }
    document.write(newString);
}

</script>
</head>

<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>


</html>

答案 1 :(得分:1)

<script type="text/javascript">中设置<head>