开发者

first and second words of a h1 tag edited using jquery?

开发者 https://www.devze.com 2023-04-12 01:09 出处:网络
How can I add a span selection on the first word of a h1 tag, and then a different span selection on the second word with jquery please?

How can I add a span selection on the first word of a h1 tag, and then a different span selection on the second word with jquery please?

For example, I would like to change:

<h1>This is a title</h1>

to

<h1><span class="firstWord">This </span><span class="secondWord">开发者_StackOverflow中文版is </span> a title</h1>


var words = $('h1').text().split(' '); // Note that split isn't jQuery, it's just javascript.

Now you have an array of words you can work with and emit back out with spans and such, e.g.:

words[0] = '<span class="firstWord">' + words[0] + '</span>';
var sentence = $('h1').text(words.split(' '));


My version:

var parts = $('h1').text().split(' ');
parts[0] = '<span class="firstWord">'+parts[0]+'</span>';
parts[1] = '<span class="secondWord">'+parts[1]+'</span>';
alert(parts.join(' '));


var splitted = $("h1").text().split(" ");

if(splitted.length > 0) {
    $("h1").html('').append("<span class='firstWord'>" + splitted[0] + "<span> ");
    if(splitted.length > 1) {
        $("h1").append("<span class='secondWord'>" + splitted[1] + "<span> ");
        for(var i=2;i<splitted.length;i++) {
            $("h1").append(splitted[i] + " ");
        }
    }
}

or see the jsFiddle


Warning: this is only safe if there's no HTML in the <h1> tag (which is why .text() is used to get the initial value). I don't think it's really possible with HTML in the <h1> tag.

var $h1 = $('h1');
h1_words = $h1.text().split(' ');
if (h1_words.length >= 2) {
    h1_words[0] = '<span class="firstWord">'+h1_words[0]+'</span>';
    h1_words[1] = '<span class="secondWord">'+h1_words[1]+'</span>';
}
$h1.html(h1_words.join(' '));


var str = $('h1').text().trim()

var strArray = str.split(' ');

var temp;

for(var i=1;i<strArray.length;i++){
   temp += strArray[i]+" "
}

var result = '<span class='firstWord'>'+strArray[0]+'</span>'+" "+temp.trim()

$('h1').text(result)


See: http://jsfiddle.net/thirtydot/Jeuu3/

$('h1').html($('h1').html().replace(/^(\w+) (\w+)/, '<span class="firstWord">$1</span> <span class="secondWord">$2</span>'));

That said, it would be better to use something more generalized, such as Lettering.js.

It's as simple as:

$('h1').lettering('words');

Then, you can add CSS for .word1 and .word2.

See: http://jsfiddle.net/thirtydot/Jeuu3/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消