您好,我正在服务器端进行验证,并返回一个带有验证错误的 JSON 对象。然后简单的 jQuery 函数将错误写入相应的 div 中:
function processEmail(data) {
$("#newEmailError").html(data.newEmail);
$("#newEmailVerificationError").html(data.newEmailVerification);
$("#changeEmailMessage").html(data.success);
}
这应该可以正常工作,但现在我测试我的应用程序并写了一些错误的电子邮件地址,然后我收到了正确的错误消息。一切看起来都不错。但现在我调整我的电子邮件和发送表单,应该只收到成功消息,但我看到了两条消息。如果没有相应的消息,看起来 div 总是获得最后一个值。我认为,例如,如果 data.newEmail 为 null(没有验证错误,并且该对象为 null),则 newEmailError div 将获得 null 值=将为空。但它只是忽略了这一点。现在我必须像这样编写我的函数并使用 .empty() :
function processEmail(data) {
$("#newEmailError").empty();
$("#newEmailVerificationError").empty();
$("#changeEmailMessage").empty();
$("#newEmailError").html(data.newEmail);
$("#newEmailVerificationError").html(data.newEmailVerification);
$("#changeEmailMessage").html(data.success);
}
有没有更好的方法来解决这个问题而不是使用 jQuery .empty() 函数?
谢谢
最佳答案
您可以使用||
跳过.empty
调用:
function processEmail(data) {
$("#newEmailError").html(data.newEmail || '');
$("#newEmailVerificationError").html(data.newEmailVerification || '');
$("#changeEmailMessage").html(data.success || '');
}
正如您在评论中指出的那样,说 .html(undefined)
没有任何用处。这是一个小沙箱,用于试验如何 .html
行为:
关于jQuery 空函数和 html 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6323875/