我对编程非常陌生,并且遇到了一些问题。 我想创建一种表单(在 html 和 javascript 中),我可以在其中进行一些计算。这是关于数字和年份的。所以首先我需要放置输入字段,我可以在其中输入年份(例如 2013 年)。该输入值将连接到多个函数:
- 计算与当年的差异(如果我要求 2018 年应该写 5,或者如果我要求 2000 iz 应写 -13 等等...)
- 检查年份是否为闰年(真/假或是/否,...)
- 计算我要求的数字的总和(2018 = 11、2013 = 6、...)
- 如果数字是质数(真/假、是/否,...)
- 反转数字(2013 = 3102、2018=8102、...)
- 显示年份的十二生肖
- 将年份转换为罗马数字(1=I、2=II、10=X、...)
我确实找到了一些功能,但我无法将其组合在一起以使其起作用。 如果有人可以提供帮助,我将非常有帮助。
我在互联网上找到的示例:
function isleap() {
var yr = document.getElementById("year").value;
if ((parseInt(yr) % 4) == 0) {
if (parseInt(yr) % 100 == 0) {
if (parseInt(yr) % 400 != 0) {
alert("Not Leap");
return "false";
}
if (parseInt(yr) % 400 == 0) {
alert("Leap");
return "true";
}
}
if (parseInt(yr) % 100 != 0) {
alert("Leap");
return "true";
}
}
if ((parseInt(yr) % 4) != 0) {
alert("Not Leap");
return "false";
}
}
反向:
<script type="text/javascript">
var year, b = 0;
year= parseInt(prompt("Enter year: "));
document.write("You've entered: " + year+ "<br />");
while(year> 0) {
b = b * 10
b = b + parseInt(year% 10)
year= parseInt(year/ 10)
}
document.write("Reverse numbers: ", b);
</script>
总和:
<script>
function find() {
var sum = 0;
var no = parseInt(frm.txt1.value);
while (no > 0) {
sum = sum + no % 10;
no = Math.floor(no / 10);
}
alert("Sum of digits " + sum);
}
</script>
<form name="frm">
Enter a Number:<input name="txt1" type="text" />
<input name="b1" onClick="find();" type="button" value="display" />
</form>
最佳答案
separate concerns 被认为是最佳实践,我使用 jQuery 作为我的 DOM抽象库 - 这真的很简单。
使用这样的输入:
<input id="b1" name="b1" type="button" value="display" />
您可以使用jQuery on method像这样:
$('#b1').on('click', function (event) {
alert('I was clicked');
});
$('#b1').on('click', function (event) {
alert('I heard that click too');
});
您可以调用任何函数:
$('#b1').on('click', isLeap);
只是不要忘记在页面上包含带有以下代码片段的 jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
关于javascript 一个输入字段连接到多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15478015/