【问题标题】:Jquery: first word color span issue for linkJquery:链接的第一个单词颜色跨度问题
【发布时间】:2015-03-16 12:56:28
【问题描述】:

第一个单词作为链接时出现问题,单词出现不正常。

     $('h3')
  .each(function () {
    var h = $(this).html();
    var index = h.indexOf(' ');
    if (index == -1) {
        index = h.length;
    }
    $(this).html('<span style="color:#fff;">' + h.substring(0, index) + '</span>' + h.substring(index, h.length));
});

当 h3 标签中的链接不出现时,看起来不错

【问题讨论】:

  • .html() 返回您选择的 HTML 中的内容。因此,如果有任何和所有文本,它也会显示您的标签。提示:如果您提供 HTML,人们更有可能帮助您并更好地理解问题。
  • 我不太确定你想达到什么目的。除了链接之外,您想对 h3 中的所有内容进行样式设置吗?也许你应该为此使用 CSS :)
  • 如果您显示一些示例 html 会有所帮助,但是您是说您想要一些 jquery 代码来设置所有 h3 元素中第一个单词的样式,而不管第一个单词是否恰好是包含在锚点等子元素中? (您当前的尝试出错了,因为它通过查找第一个空格来工作,该空格位于 &lt;a&gt; 标记的属性内。)

标签: javascript jquery


【解决方案1】:

您不能在 span 元素中使用颜色来设置标签中的颜色。您需要在标签本身中设置颜色:

$('h3').each(function () {
    if($(this).contents().first().is('a')){
        $(this).contents().first().css('color','#fff');
    }else {
        var node = $(this).contents().filter(function(){
            return this.nodeType == 3;
        }).first();
        var text = node.text();
        var first = text.slice(0, text.indexOf(" "));
        node[0].nodeValue = text.slice(first.length);
        node.before('<span style="color:#fff">' + first + '</span>');
    }
});
h3{
  background: #f00;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3><a>test</a> word</h3>
<h3>test word</h3>

第一个单词选择器的代码取自here

【讨论】:

    【解决方案2】:

    试试这样的:http://jsfiddle.net/jnmwyagy/2/

    <h3><a href="#">google</a><p><span class="text">First</span> Word</p></h3>
    <h3><a href="#">google</a><p><span class="text">First</span> Word</p></h3>
    

    jQuery

     $('h3')
         .each(function () {
         $(this).find('.text').css("color", "red");
     });
    

    【讨论】:

      【解决方案3】:

      尝试搜索打开的a 标签,而不是空格。

      $('h3').each(function () {
          var h = $(this).html();
          var index = h.indexOf('<a');
          if (index == -1) {
              index = h.length;
          }
          $(this).html('<span style="color:#fff;">' + h.substring(0, index) + '</span>' + h.substring(index, h.length));
      });
      

      说真的,最好只为 h3a 标签应用 CSS 样式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-12
        • 2011-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多