Jquery:链接的第一个单词颜色跨度问题

时间:2015-01-18 11:14:02

标签: javascript jquery

当链接时,第一个单词出现问题,单词显示不正常。

     $('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));
});

problem behaviour

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

nice behaviour

3 个答案:

答案 0 :(得分:0)

尝试这样的事情: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");
 });

答案 1 :(得分:0)

尝试搜索开放的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样式。

答案 2 :(得分:0)

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

&#13;
&#13;
$('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>');
    }
});
&#13;
h3{
  background: #f00;
  }
&#13;
<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>
&#13;
&#13;
&#13;

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

相关问题