嗨,我不是很好的JavaScript,但我想尝试使用JavaScript进行虚拟状态更新。如果在输入状态更新后单击按钮,则会将其添加到流中。我希望当用户按下Enter键同时更新流时,不要只是单击按钮来执行此操作。
这是我的代码
<script>
$(document).ready(function(){
var newStatus;
var minLength=1;
$("button#update").click(function(){
newStatus=$.trim($("input#status").val()); // get status
if(newStatus.length>minLength)
{
$("div#streaming").prepend('<div class="status newStatus clearfix"><div class="avatar"><img src="img/avatars/thumb_avatar_5.gif" alt="test" class="avatar-40 right-20" /></div><div class="content"><p><a href="#">Username</a> '+newStatus+'</p><p class="font11"><em>Seconds ago</em> ⋅ <a href="#" class="lightblue">Comment</a> ⋅ <a href="#" class="lightblue">Share</a></p></div></div>');
$('.newStatus').animate({opacity: 3.0}, 30);
$("input#status").val('').focus(); // clear status box
}
else
{
alert("Please share something");
}
});
});
</script>
<span class="left inset streamupdate">
<input type="text" placeholder="Share Something" title="Share Something" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;" id="status" />
<button id="update" value="Go" type="button"></button>
</span>
<div id="streaming"></div>
答案 0 :(得分:0)
将表单元素包装在表单标记中并设置onsubmit以运行您的函数。
$(document).ready(function(){
var newStatus;
var minLength=1;
$("#update").click(function(){
buttonClick();
});
});
function buttonClick() {
newStatus=$.trim($("input#status").val()); // get status
if(newStatus.length>minLength) {
$("div#streaming").prepend('<div class="status newStatus clearfix"><div class="avatar"><img src="img/avatars/thumb_avatar_5.gif" alt="test" class="avatar-40 right-20" /></div><div class="content"><p><a href="#">Username</a> '+newStatus+'</p><p class="font11"><em>Seconds ago</em> ⋅ <a href="#" class="lightblue">Comment</a> ⋅ <a href="#" class="lightblue">Share</a></p></div></div>');
$('.newStatus').animate({opacity: 3.0}, 30);
$("input#status").val('').focus(); // clear status box
} else {
alert("Please share something");
}
}
<form onsubmit="buttonClick()">