[英]Changes made by submit button via JQuery and JavaScript function do not last
I am trying to write some text on the document using the document.write() method. 我正在尝试使用document.write()方法在文档上写一些文本。 Thing is i want this text to be written there when user clicks button, and remain there after the user is done clicking the button.
我要的是在用户单击按钮时将此文本写在此处,并在用户单击按钮完成后保留在此处。 The problem I'm having right now is that the text appears for a moment and then disappears after function is done executing, which is something I do not want nor do not know how to fix it.
我现在遇到的问题是,文本会出现一会儿,然后在函数执行完毕后消失,这是我既不希望也不知道如何解决的问题。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Learning JQuery</title>
<meta charset="utf-8" />
<script src="jquery.js" type="text/javascript"></script>
<script type="script.js">
$(document).ready(function(){
$("input").click(function(){
for(var i = 0; i < 10; i++){
for(var j = 0; j < i; j++){
document.write("*");
}
document.write("<br/>");
}
//alert("click to continue");
});
});
</script>
</head>
<body>
<p>Body section of the page</p>
<form>
<input type="submit" value="clickMe" />
</form>
</body>
</html>
The text " appears for a moment and then disappears " because your page refreshes due to the type="submit"
in you submit button. 文本“ 出现片刻,然后消失 ”,因为您的页面由于您提交按钮中的
type="submit"
而刷新。
You can use preventDefault()
if you are trying to prevent the page from refreshing. 如果试图阻止页面刷新,则可以使用
preventDefault()
。
$(document).ready(function(){
$("input").click(function(e){
e.preventDefault();
for(var i = 0; i < 10; i++){
for(var j = 0; j < i; j++){
document.write("*");
}
document.write("<br/>");
}
//alert("click to continue");
});
});
Alternatively, you can rather use a normal button if you are not actually submitting form data: 另外,如果您实际上并未提交表单数据,则可以使用普通按钮:
<button id="button">Click Me</button>
and then fire the js when the button is clicked: $("#button").click(function(e){ ... });
然后在单击按钮时触发js:
$("#button").click(function(e){ ... });
Use something like below, 使用类似下面的内容,
On the body put a div. 在身体上放一个div。
<div id="my-div"></div>
Then in your code, you can do this inside click 然后在您的代码中,可以在内部单击
e.preventDefault();
for(var i = 0; i < 10; i++){
for(var j = 0; j < i; j++){
$('#my-div').append("*");
}
$('#my-div').append("<br/>");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.