1

在 Javascript 中,我试图采用输入到字段中的全名(名字、中间名和姓氏),一旦单击提交按钮,输出到三个单独的字段字符长度、中间名和 3 个首字母。到目前为止,我已经进入了字符字段,但我对如何获取两个空格之间的信息感到困惑。

// strings.js
// This script takes a name and spits out its character length with initials.

// Function called when the form is submitted.
// Function performs the calculation and returns false.
function formatNames() {
'use strict';

// For storing the Full Name, Middle name, initials, length:
var lengthName;
var middleName;
var yourInitials;


// Get a reference to the form values:
var fullName = document.getElementById('fullName').value;

// Perform the character spit out:
lengthName = fullName.length;

// Pull out the middle name:

// Display the volume:
document.getElementById('nameLength').value = lengthName;

// Return false to prevent submission:
return false;

} // End of formatNames() function.

// Function called when the window has been loaded.
// Function needs to add an event listener to the form.
function init() {
'use strict';
document.getElementById('theForm').onsubmit = formatNames;
} // End of init() function.
window.onload = init;
4

1 回答 1

1

这听起来像是家庭作业,所以我会给你一些提示,而不会破坏学习体验。

您可以split(' ')在字符串上使用来获取该字符串中的单词数组(由空格分隔)。

您可以charAt(0)在字符串上使用来获取字符串的第一个字母。

于 2012-10-23T13:58:14.143 回答