如果元素是特定字符,如何将元素中的最后一个字符包装起来?

问题描述 投票:0回答:1

我是这样来回的,但我觉得我很亲密。我想用div .content包装所有H1标签的最后一个字符,如果它是句号或问号(应用颜色)。这是我有的:

$(function() {
    $('.content h1').each(function() {
        last = $(this).text().trim().slice(-1);
        if(last === '.' || last === '?') {
            alert(last);
            //last.wrap('<span class="orange-end"></span>');
        }
    });
});

这将正确警告最后一个角色,我只是努力包裹并返回。

干杯全都。

javascript jquery
1个回答
2
投票

$(function() {
    $('.content h1').each(function() {
      // get the text
      var text = this.innerHTML.trim();
      
      //do logic if the last character is a period or question mark
      if (['.', '?'].indexOf(text.slice(-1)) > -1) {
        // set the html back to what it was, replacing the last 
        // character with the wrapped html
        this.innerHTML = text.slice(0, -1) 
                       + '<span class="orange-end">'
                       + text.slice(-1)
                       + '</span>'; 
      }
    });
});
.orange-end { color: orange; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
  <h1>What is the meaning of this?</h1>
  <h1>No way!</h1>
  <h1>I know.</h1>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.