2016-11-15 11 views
0

divを見て、最初の単語を叩くjQueryがあります。これはうまく動作しますが、そのdivには1つの単語しかない場合、私はそれを打ち切りたいとは思いません。jQuery - divに2つの単語がある場合、最初の単語を打ち破る

誰でもこれを達成する方法を知っていますか?

コード:

jQuery('.class').each(function(index) { 

//get the first word 
var firstWord = $(this).text().split(' ')[0]; 

//wrap it with strike 
var replaceWord = "<strike>" + firstWord + "</strike>"; 

//create new string with span included 
var newString = $(this).html().replace(firstWord, replaceWord); 

//apply to the divs 
jQuery(this).html(newString); 
}); 
+1

good ol'ififはどうですか? –

+0

'$(this).text()。split( '').length> 1 'の長さをチェックしてから、何かを打ち切ります – Developer

答えて

1
jQuery('.class').each(function(index) { 

// get the word array 
var words = $(this).text().split(' ') 

if (words.length === 1) { 
    // nothing to see here 
    } 
else 
    { 
    //get the first word 
    var firstWord = $(this).text().split(' ')[0]; 

    //wrap it with strike 
    var replaceWord = "<strike>" + firstWord + "</strike>"; 

    //create new string with span included 
    var newString = $(this).html().replace(firstWord, replaceWord); 

    //apply to the divs 
    jQuery(this).html(newString); 
    } 

}); 
+0

パーフェクト - ありがとう –

+0

これが正しい答えだったらクリックしてくださいそのことを示すチェックマーク。ありがとう。 –

0

あなたは2番目の単語が実際に存在していることを確認だけにしてあなたのコードを実行するために、いくつかの可能な条件のいずれかを使用することができます。一つの例はこれです:

AB Udhayによって示唆されるように、それはこのようにそれを分割する前に、トリム()を使用することは常に良いでしょう。)

jQuery('.class').each(function(index) { 

var words = $(this).text().trim().split(' '); 
//get the first word 
var firstWord = words[0]; 

if(typeof words[1] !== "undefined") 
{ 

//wrap it with strike 
var replaceWord = "<strike>" + firstWord + "</strike>"; 

//create new string with span included 
var newString = $(this).html().replace(firstWord, replaceWord); 

//apply to the divs 
jQuery(this).html(newString); 
}//if there's second word also 
}); 
0

あなたはこのコード

のように、 $(this).text().split(' ').length > 1をチェックカント
jQuery('.class').each(function(index) { 

    if($(this).text().split(' ').length > 1){ 

     //get the first word 
     var firstWord = $(this).text().split(' ')[0]; 

     //wrap it with strike 
     var replaceWord = "<strike>" + firstWord + "</strike>"; 

     //create new string with span included 
     var newString = $(this).html().replace(firstWord, replaceWord); 

     //apply to the divs 
     jQuery(this).html(newString); 

    } 

}); 
関連する問題