我需要在用户在 input 中输入数据后更新 div,但我不能。 div 出现,但随后消失。
我的代码:
函数.js
window.onload = function(){
var mydata = document.getElementsByTagName("input");
if(mydata != null){
for(var i=0; i< mydata.length; i++) {
if(mydata[i].type == "text"){
if(mydata[i].id == "qtd") {
mydata[i].onchange = function () {
send(this);
};
}
}
}
}
}
function send(box){
if (box == null) { return; }
var nameBox = box.name;
var url="process.php?nameBox="+nameBox+"&value="+encodeURIComponent(box.value);
requisicaoHTTP("GET",url,true);
}
function dataNew(){
var info = ajax.responseText;
if(info != null){
var out= document.getElementById("myDIV");
out.innerHTML = info;
}
}
HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="Ajax.js"></script>
<script type="text/javascript" src="functions.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form action="javascript:void%200">
<input type="text" name="test" id="test" value="">
</form>
<div id="myDIV"></div>
</body>
</html>
我希望 div 在输入数据后显示并更新。
最佳答案
您可以使用 jQuery 的 .html 函数。
$('#txt_box').keyup(function(event){
// Get the typed text
var txt = $(this).val();
// Insert the text to the div
$("#myDIV").html(txt);
});
(记住将 jQuery 添加到您的代码中)
更新
所以你的代码的完整功能应该是这样的:
HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript" src="functions.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form id="txt_form" action="">
<input type="text" name="test" id="test" value="">
<input type="submit" value="Submit" id="txt_send">
</form>
<div id="myDIV"></div>
</body>
</html>
函数.js
$("#txt_send").click(function(event){
event.preventDefault();
var field_name = $("#test").attr("name");
var field_val = $("#test").val();
// POST to update the text.
$.ajax({
type: "POST",
url: "process.php?nameBox="+field_name+"&value="+encodeURIComponent(field_val),
dataType: "html"
}).done(function(data) {
// Display the text on the div.
$("#myDIV").html(field_val);
}
});
});
});
Full Code Fiddle Example 我注释掉了 Ajax,因为 fiddle 上当然没有 php。
关于PHP和Json,在input中输入数据后更新div。不行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37060297/