jQuery 空函数和 html 函数

标签 jquery html ajax spring

您好,我正在服务器端进行验证,并返回一个带有验证错误的 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行为:

http://jsfiddle.net/ambiguous/zgbnB/1/

关于jQuery 空函数和 html 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6323875/

相关文章:

c# - JavaScript : pass an array to WCF service (c#)

jquery - CSS:以div为中心旋转文本

javascript - 选择国家时改变颜色

javascript - 将 Ionic 标签从 ts 文件附加到 html

php - 如何在数据库php/mysql中存储图片链接

java - ajax 将序列化表单和模型列表发布到 Controller 方法

php - 如何实现依赖输入字段的Jquery?

javascript - 500 内部服务器错误 ajax/javascript

javascript - 加载我的网站时从我的服务器获取图像

javascript - 带有文本的 CSS 动画故障