你好所以我对 html 和 javascript 比较陌生,我目前想制作一个页面来完成某些操作,例如查找数字数组的最大数量和数字的阶乘,如下所示。
这是我组织这些部分的方式
<!DOCTYPE html>
<html lang = "en">
<head>
<title>HTML/CSS Responsive Theme</title>
<meta charset = "utf-8">
<link rel = "stylesheet" href = "main.css" type = "text/css">
<meta name = "viewport" content = "width=device-width, initial-scale=1.0">
<script>
function startFactorial(number)
{
function factorial(num)
{
if(num <= 1)
return 1;
return num * factorial(num - 1);
}
document.factorials.factorialsfield.value = factorial(number);
}
function startMaxofFive(str)
{
//can actually find the max of n numbers not limited to 5
function maxoffive(string)
{
var nums = (string.match(/[-]?\d+/g));
var b = nums.map(Number);
return Math.max.apply(Math,b);
}
document.mof.moffield.value = (maxoffive(str));
}
</script>
</head>
<body>
<section id = "first">
<h3>Factorial</h3>
<form name= "factorials">
Enter a number <input type = "number" name = "factorialsfield" value = 0>
<br><br>
<input type = "button" onClick = "startFactorial(factorialsfield.value)" value = "Calculate"/>
</form>
</section>
<br>
<section id = "second">
<h3>Max of Five Numbers</h3>
<form name = "mof">
Enter 5 numbers <input type = "text" name = "moffield" placeholder = " separate each number by commas" size = 26>
<br><br>
<input type = "button" onClick = startMaxofFive(moffield.value) value = "Calculate"/>
</form>
</section>
<br>
<section id = "third">
<h3>Sum and Multiply</h3>
<form name = "operations">
Enter numbers to apply operations <input type = "text" name = "operationsfield"
</form>
</section>
</body>
</html>
我想问大家的是,有没有更好的方法来访问我的脚本中的这些函数,而不必创建另一个函数来使用它们?
最佳答案
这里有一些建议:
您可以使用
document.getElementById( id )
获取特定元素,其中 id 是 HTML 的元素 ID<element id="id_name">
.事件允许您根据用户输入触发操作。它的工作原理基本相同,但您不再需要为函数命名:
element_variable.event = function() { /* ... */ }
看看内部函数是否真的需要;看看你是否可以在你不再需要该功能的地方编辑代码(
document.getElementById
可能会让你做那些事情)
例子:
<form id="factorials" name="factorials">
<!-- Skipping input -->
<input type="submit" <!-- ... -> />
</form>
// Javascript file
var fact = document.getElementById( "factorials" );
fact.onsubmit = function() {
/* Your code here */
}
关于javascript - 应用 JavaScript 脚本的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29040202/