我可以在没有服务器的情况下执行此操作吗?

时间:2019-10-31 03:26:04

标签: javascript html

我还没有后端技能,我只是想确定是否可以使用javascript创建此功能并在浏览器上运行它。

我想要一个生日输入字段和一个提交按钮。

我想获取生日数据,并将所有单独的数字加在一起,然后将总和的数字相加得到一个数字。

例如:

10/9/1940将计算1 + 0 + 9 + 1 + 9 + 4 + 0。等于24。然后将数字2 + 4相加。等于6。

然后,我想在h1的末尾打印该数字,说:“您的综合生日数字是:6”

有什么提示吗?我不知道如何将生日表格中的输入数据链接到提交按钮。

4 个答案:

答案 0 :(得分:4)

是-如果您不需要重新加载页面即可保留的信息,则可以使用JavaScript进行几乎所有操作。您的用例与W3Schools' JS tutorial并没有什么不同-除了按钮之外,该表单还需要一个日期输入字段和几行内容来进行计算并将更改应用于页面。我建议您仔细阅读一下以了解各种可能性。

仅当您希望系统自主运行或记住多个用户时才需要服务器。

答案 1 :(得分:1)

尝试使用parseInt()来检查其是否为数字。

function sumString(str, result) {
  for (i = 0; i < str.length; i++)
    if (!isNaN(parseInt(str[i])))
      result += parseInt(str[i]);
  if (result.toString().length <= 1)
    return result;
  else
    return sumString(result.toString(), 0);
}


function onBirthDaySelect(value) {
  document.getElementById('result').innerHTML = `<h1>your combined birthday number is: ${sumString(value, 0)}</h1>`;
}
<input type="date" id="bday"> <button onclick="onBirthDaySelect(document.getElementById('bday').value)">Calculate</button>
<div id="result"></div>

答案 2 :(得分:0)

使用Javascript,您可以从生日输入字段中解析日期,请参阅js字符串方法,将字符串解析为数字后,您可以轻松地将它们加起来然后放回到页面中。

答案 3 :(得分:0)

是的,可以。通过使用input date,您可以获取日期,然后通过对每个索引使用Number(),将值转换为整数,最后通过使用<h1>文本将其附加到正文中  appendChild

function calculate(){
  const date = document.getElementById('birthdate').value; // get input date value
  let result = 0; // for each function call set result to 0
  for (let index=0; index < date.length; index++){
    if(Number(date[index])){ // check if number
      result += Number(date[index]); // accumulate result
    }
  }
  const node = document.createElement("h1"); // Create a <h1> node
  const textnode = document.createTextNode(`your combined birthday number is: ${result}`);
  node.appendChild(textnode); // Append the text to <h1>
  document.body.appendChild(node); // Append <h1> to <body>
}
<input type="date" id="birthdate">
<button onclick="calculate()">Calculate</button>

服务器通常用于存储数据和管理数据,以便您可以在多个设备上使用它们。在这种情况下,您实际上并不需要一个。