【问题标题】:Replace value with image using Jquery?使用 Jquery 用图像替换值?
【发布时间】:2023-03-13 20:07:01
【问题描述】:

我有一个包含很多 cmets 的页面。

代码结构如下:

+ <li id="li-comment-65" class="comment even thread-odd thread-alt depth-1">
     <div class="comment-body">
        <div id="comment-65">
           <div class="comment-author vcard">
              <img height="30" width="30" href="" alt="" />                        
              <cite class="fn">keith</cite>                  
           </div>
           <div class="comment-meta commentmetadata">
              <a href="#">June 16, 2009 at 10:21 pm</a>
           </div>
           <div id="rating-65" class="rating-class">Excellent</div>
           <p>Hiya</p>
        </div>
     </div>
  </li>

我想做的是:

  1. 从每个 'rating-class' 类中获取值。 (最多有 5 个值: 一种。优秀 湾。很好 C。好的 d。较差的 e.很差
  2. 如果评级 == '优秀' - 显示 5 星图片并删除“优秀”文字
  3. 如果评级 == '非常好' - 显示 4 星图片并删除“非常好”文字
  4. ...
  5. ...

这很难做到吗?

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    应该这样做:

    $('div.rating-class').each(function() {
        var value = $.trim($(this).text());
        var src;
        switch(value) {
            case 'Excellent':
                src = 'fivestars.png';
                break;
            case 'Very Good':
                src = 'fourstars.png';
                break;
            ...                     
        }
        $img = $('<img/>').attr('src', src);
        $(this).html($img);
    });
    

    最好是这样做:

    $('div.rating-class').each(function() {
        var value = $.trim($(this).text()).replace(' ', '_').toLowerCase();
        $(this).addClass(value);
    });
    

    然后有这样的 CSS 类:

    div.rating-class.excellent {
        background-image: url(fivestars.png);
        text-indent: -1000px;
    }
    div.rating-class.very_good {
        background-image: url(fourstars.png);
        text-indent: -1000px;
    }
    ...
    

    文本缩进会隐藏你原来在那里的常规文本。

    【讨论】:

    • 非常感谢保罗。我真的很感谢你的好意和帮助!
    猜你喜欢
    • 1970-01-01
    • 2018-03-27
    • 2011-07-11
    • 2014-12-21
    • 2014-10-09
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    相关资源
    最近更新 更多