如何防止Jquery追加多次
我有一些 jQuery 来检查用户是否输入了正确的电子邮件地址。如果电子邮件无效,用户可以返回并更改他/她的电子邮件。但是,我的代码将导致相同的错误消息两次,因为错误不断附加到我的 errors
div 中。如何更改此设置以仅允许附加错误一次?如果 email
变量为 true
,我还想删除该错误。此 div 中还存在其他验证错误。
jQuery:
var email = $('#email').val();
email = validateEmail(email);
if (email = "false") {
$('#errors').append("<p>Please enter a valid email</p>");
}
validateEmail
将返回 true
或 false
,具体取决于电子邮件是否有效。
I have some jQuery that checks if the user inputted a correct email address. The user can then go back and change his/her email if it is not valid. However, my code will result in the same error messege twice because the error keeps getting appended inside my errors
div. How can I change this to only allow the error to be appended once? I also would like to remove the error if the email
variable is true
. There are also other validation errors being placed in this div.
jQuery:
var email = $('#email').val();
email = validateEmail(email);
if (email = "false") {
$('#errors').append("<p>Please enter a valid email</p>");
}
validateEmail
will return either true
or false
depending on whether the email is valid.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当您附加电子邮件错误时,请使用类“emailerror”指定它,
但在附加之前,只需删除具有类“emailerror”的错误
when u append the email error, specity it with a class "emailerror",
but before append, just remove that error which have class "emailerror"
尝试在附加新信息(即新错误)之前清除该值:
Try clearing the value before appending new information, ie new errors:
使用
html()
或text()
设置错误的内容div
:并且在
email 为
true
,请在if
语句中添加else
:另请注意,我使用了
===
=
。这是因为使用单个等号 (=
) 只会将变量email
设置为false
而不会实际检查是否相等。Use
html()
ortext()
to set the content of the errorsdiv
:And to not display anything when
email
istrue
, add anelse
to yourif
statement:Also note that I used
===
instead of=
. This is because using a single equals sign (=
) will just set the variableemail
tofalse
and not actually check for equality.更合适的方法是从 DOM 树中删除所有附加代码:
试试这个:
More appropriate way is to remove all the appended code from DOM tree:
Try this:
您需要做的就是在条件之后添加
$('.append').remove()
,然后在要附加的文本中使用p
标记并添加一个class="append"
它效果很好all you need to do is add a
$('.appended').remove()
right after your conditional, then in the text you are appending, use ap
tag and add aclass="appended"
it works well