<html>
<head>
<script type="text/javascript">
function add(a,b) {
var result = parseInt(a) + parseInt(b)
return result
}
</script>
</head>
<body>
<input type="text" name="numberOne" id="txtNumberOne" />
<input type="text" name="numberTwo" id="txtNumberTwo" />
<!-- <input type="button" id="btnClick" value="Add" /> -->
<button id="btnClick">Add</button>
<p id="answer"></p>
<script>
document.getElementById("btnClick").addEventListener("click", function(){
var view = add(document.getElementById('txtNumberOne').value, document.getElementById('txtNumberTwo').value )
document.getElementById("answer").innerHTML = view;
});
</script>
</body>
</html>
问题:
当调用具有返回值的函数时,我将如何捕获结果并显示它?
上面的代码是这样做的,然而,这样做是正确的做法吗?我创建了一个addListnerEvent,当用户点击按钮时,它调用返回答案的函数,innerHTML显示答案。如果没有,那么正确的做法是什么?
答案 0 :(得分:0)
我就是这样做的。但请注意,我缺少一些相关信息。几个笔记:
document.querySelector()
语法,这与jQuery和其他库使用的语法更相似See the demo it in jsfiddle。代码:
<html>
<body>
<!-- inputs belong to a form -->
<form class="totalpayment">
<input class="paid" type="text" name="numberOne" />
<input class="due" type="text" name="numberTwo" />
<button class="gettotal">Add</button>
</form>
<p class="total"></p>
<!-- scripts are better at the end of the body -->
<script>
// Retrieve a number from an input element
function getNumber(selector) {
var rawValue = document.querySelector(selector).value;
return parseInt(rawValue);
}
// Sum the value when submitting the form
document.querySelector(".totalpayment").addEventListener("submit", function(e){
e.preventDefault();
var paid = getNumber('.paid');
var due = getNumber('.due');
document.querySelector(".total").innerHTML = paid + due;
});
</script>
</body>
</html>
或者使用jQuery,使用它可以让您的生活更轻松,而且非常普遍。 See the demo it in jsfiddle。代码:
<html>
<body>
<form class="totalpayment">
<input class="paid" type="text" name="numberOne" />
<input class="due" type="text" name="numberTwo" />
<button>Add</button>
</form>
<p class="total"></p>
<script src="jquery.min.js"></script>
<script>
// Sum the value when submitting the form
$(".totalpayment").submit(function(e){
e.preventDefault();
var paid = parseInt($('.paid').val());
var due = parseInt($('.due').val());
$(".total").html(paid + due);
});
</script>
</body>
</html>
当不使用库时,addEventListener和innerHTML都是当前的最佳实践(无论如何都要好于element.onclick
或内联onclick
)。