【问题标题】:How to style text in .html() in jquery如何在 jquery 的 .html() 中设置文本样式
【发布时间】:2015-04-01 18:56:23
【问题描述】:

我想为 html() 中的文本设置样式,例如 color:red; font-weight:bold。我怎样才能在 jQuery 本身中做到这一点?我可以在 html 中使用 id=login_result 设置 div 的样式,但是这里的每个文本都是红色和粗体。我只希望下面的这些错误文本是红色的。非常感谢

var login_result = $('#login_result');

if ($.trim(email.val()).length == 0) {
    email.focus(); // focus to the filed
    login_result.html('<span> Email field is required</span>');
    return false;
}

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    首先给 span 元素添加类

    if ($.trim(email.val()).length == 0) {
        email.focus(); // focus to the filed
        login_result.html($('<span> Email field is required</span>').addClass('error'));
        return false;
    }
    

    然后在 CSS 文件中描述该类

    .error{
        color:red;
        font-weight:bold;
    }
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      login_result
         .html('<span style="color:red;font-weight:bold">Email field is required</span>');
      

      或者:

      login_result.html('<span>Email field is required</span>');
      login_result.find('span').css({'color': 'red', 'font-weight': 'bold'});
      

      但最好的做法是使用 CSS 类:

      login_result.html('<span class="validation-message">Email field is required</span>');
      

      (然后将必要的样式放入 CSS 文件中)。

      【讨论】:

        【解决方案3】:

        插入新的 html 后,css 将应用,例如:

        #login_result span {
            color:red
        }
        

        将使您的新跨度文本变为红色。

        【讨论】:

          【解决方案4】:

          您可以向 span 添加一个类并在样式表中定义它:

          var login_result = $('#login_result');
          if ($.trim(email.val()).length == 0) {
            email.focus(); // focus to the filed
            login_result.html('<span class="error"> Email field is required</span>');
            return false;
          }
          .error {
            color: red;
          }

          与 Brad Martin 的解决方案相比,这具有优势,所有关于样式的信息都设置在您的样式表中,而不是在应该主要处理应用程序逻辑的 javascript 中。

          【讨论】:

          • 谢谢,我在问这个问题之前试过这个方法,但我没有清除缓存,它没有按预期工作。我以为我做错了什么。现在我看到了你的答案,是的,问题来自缓存。
          【解决方案5】:

          尝试在 login_result.html('') 行末尾使用 .css() 方法

          var login_result = $('#login_result');
          if ($.trim(email.val()).length == 0) {
              email.focus(); // focus to the filed
              login_result.html('<span> Email field is required</span>').css('color', 'red');
              return false;
          }
          

          【讨论】:

          • 这会将样式添加到#login_result 而不是跨度。
          • Gotcha,只是一个即兴的答案,让用户尝试一些方法并学习一点。似乎他已经掌握了一些不错的 jQuery 知识,如果您查看文档,找到他自己的答案不会太难。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-09
          • 2012-05-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多