我想使用jQuery来获取用户输入并传入函数并更新" div"而不是PHP。 我的HTML(包括脚本)代码是:
<head>
<title>Mobile Locale test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content="Mobile Locale this is!" />
<script>
var x;
$(document).ready(function()
{
x = $("#q").val();
var name = "Hello " + x + ". Welcome to this site";
$("#test").text(name);
});
console.log(x);
</script>
</head>
<body>
<form>
<input type="text" id="q" placeholder="Your name please...">
<button id="submit">Submit!</button>
<div id="test">This should change...</div>
</form>
</body>
我想要的: 我想从用户那里获得输入并将该输入分配给x。 然后我想完成一个字符串并在该字符串中传递x。 然后我想在div id =&#34; test&#34;。
中写出完整的句子我绊倒这个超过6个小时却没有成功。试过很多代码但失败了。 提到了w3schools jQuery表单示例,但他们使用的是form method =&#34; abcd.asp&#34;。
提前致谢...
答案 0 :(得分:2)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jquery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var x;
$(document).ready(function()
{
var x = $("input#q").val();
var name = "Hello " + x + ". Welcome to this site";
$("#test").text(name);
});
function CallSubmit()
{
var x = $("input#q").val();
var name = "Hello " + x + ". Welcome to this site";
$("#test").text(name);
return false;
}
</script>
</head>
<body>
<form>
<input type="text" id="q" placeholder="Your name please...">
<button id="submit" onclick="return CallSubmit();">Submit!</button>
<div id="test">This should change...</div>
</form>
</body>
</html>
答案 1 :(得分:0)
您的脚本在页面加载时执行,当input
为空时 - 调用事件上的代码,例如keyup
$(document).ready(function(){
$("#q").keyup(function() {
var name = "Hello " + this.value + ". Welcome to this site";
$("#test").text(name);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="q" placeholder="Your name please...">
<button id="submit">Submit!</button>
<div id="test">This should change...</div>
答案 2 :(得分:0)
您可以将focusout
事件与input
绑定,以动态更改div。另一种方法是更新每个keypress
。
$(document).ready(function () {
$('#q').keypress(function (event) {
if (event.which == 13) {
event.preventDefault();
if ($(this).val() != '') {
var x = $(this).val();
var name = "Your string " + x;
}
$('#test').text(name);
}
});
});
答案 3 :(得分:0)
您可以在按钮的点击事件中获取名称。 工作示例:http://jsfiddle.net/jjjoeupp/
$('#submit').on('click', function()
{
x = $("#q").val();
var name = "Hello " + x + ". Welcome to this site";
$("#test").text(name);
});
Hope it helps!!!