jquery insertAfter 或追加问题
我正在尝试验证表单输入。
现在我只是享受在输入后显示一条消息的乐趣。 我使用 after() 方法来显示简单的文本,当我故意在框中犯错误时,我会完美地显示消息。
但是,如果我故意再次犯错,它会立即在第一个错误消息之后添加相同的消息。
有没有办法替代原来的方法?我不想尝试添加更多代码来查找原始错误消息,将其删除,然后再次插入相同的消息。
如果有必要的话我会的,但我想我应该先问一下。
这是我的代码:
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$("form#testform").submit(function(){
if($("#fieldname1").val().length < 5){ $("#fieldone").after("<div>not enough characters</div>"); }
});return false;
});
</script>
<form id="testform" method="post">
<table>
<tr>
<td style="width:100px;">Field One:</td>
<td><input type="text" name="fieldname1" id="fieldname1" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit" /></td>
</tr>
</table>
</form>
I am playing around with validating form inputs.
For now I'm simply having fun with displaying a message after the input.
I'm using the after() method to display simple text, and when I purposely make a mistake in the box I display the message perfectly.
However, if I purposely make a mistake again, it immediately adds the same message after the first error message.
Is there a method that replaces the original? I didn't want to try to add some more code to look for that original error message, delete it, and then insert the same message again.
I will if I have to, but I thought I'd ask first.
Here's my code:
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$("form#testform").submit(function(){
if($("#fieldname1").val().length < 5){ $("#fieldone").after("<div>not enough characters</div>"); }
});return false;
});
</script>
<form id="testform" method="post">
<table>
<tr>
<td style="width:100px;">Field One:</td>
<td><input type="text" name="fieldname1" id="fieldname1" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit" /></td>
</tr>
</table>
</form>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想象做这样的事情是理想的:
你在树中查找父级(),然后如果你找到一个 div 子级,你就知道该消息已经存在。否则,添加它。
现在,我认为更好的选择是稍微不同地构造 HTML,但这是一个不同的讨论。
I'd imagine doing something like this would be ideal:
You look up the tree to the parent (<td>), and then if you find a div child, you know that message already exists. Else, add it.
Now, I think a better choice would be to structure your HTML a bit differently, but that's a different discussion.
您需要将 id“fieldone” 添加到您要附加的元素中,您发布的那段代码中缺少它。
编辑:Beamrider 你先到达那里:) +1
You need to add id "fieldone" to the element you are appending to, it's missing from that bit of code you posted.
EDIT: Beamrider you got there first :) +1