如何使用JavaScript更新/更改HTML内容并防止页面刷新? [英] How to update/change HTML content with JavaScript and prevent the page from refreshing?
问题描述
,网页不断刷新。
如何防止页面刷新?
Javascript:
function showResult(form ){
var coba = form.willbeshown.value;
var coba2 = coba + 2;
document.getElementById(showresulthere)。innerHTML = coba2;
}
HTML $ b
< form>
< input type =textname =willbeshownvalue =>
< button onclick =showResult(this.form)> Ganti1< / button>
< / form>
< / body>
不要使用表单。您没有将任何表单数据提交给服务器。要在浏览器中处理数据,您不需要表单。使用表单只会使事情复杂化(尽管这些问题可以通过在按钮
元素中使用 type = button
来解决,阻止它作为提交按钮)。
< input type =textid =willbeshownvalue = >
< button onclick =
showResult(document.getElementById('willbeshown'))> Ganti1< / button>
< script>
function showResult(elem){
document.getElementById(showresulthere)。innerHTML = Number(elem.value)+ 2;
}
< / script>
我已经使用了转换为数字, Number()
,因为我想你想在数值上加2到字段值,例如42 + 2制作44而不是一个字符串,42 + 2制作422(这是默认情况下会发生的情况,如果您只是使用输入元素的值并添加一些内容。
I'm a newbie to scripting. I want to update HTML content with JavaScript, but as you can see the web page keeps refreshing.
How can I prevent the page from refreshing?
Javascript:
function showResult(form) {
var coba=form.willbeshown.value;
var coba2=coba+2;
document.getElementById("showresulthere").innerHTML=coba2;
}
HTML
<form>
<input type="text" name="willbeshown" value="">
<button onclick="showResult(this.form)">Ganti1</button>
</form>
<p id="showresulthere">Result will be shown here</p>
</body>
Don’t use a form at all. You are not submitting any form data to a server. To process data in the browser, you don’t need a form. Using a form just complicates things (though such issues could be fixed by using type=button
in the button
element, to prevent it from acting as a submit button).
<input type="text" id="willbeshown" value="">
<button onclick=
"showResult(document.getElementById('willbeshown'))">Ganti1</button>
<p id="showresulthere">Result will be shown here</p>
<script>
function showResult(elem) {
document.getElementById("showresulthere").innerHTML = Number(elem.value) + 2;
}
</script>
I have used conversion to numeric, Number()
, as I suppose you want to add 2 to the field value numerically, e.g. 42 + 2 making 44 and not as a string, 42 + 2 making 422 (which is what happens by default if you just use an input element’s value and add something to it.
这篇关于如何使用JavaScript更新/更改HTML内容并防止页面刷新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!