2016-11-15 56 views
0

我有一塊jQuery,它看着一個div,並擊穿第一個單詞。這工作正常,但如果該div只有一個詞,我不希望它通過。jQuery的 - 如果div有兩個單詞,通過第一個字

任何人都知道如何做到這一點?

代碼:

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

好的ol''if'怎麼樣? –

+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

可以使用任何的幾種可能情況,以確定其實是有一個第二個字和運行您的代碼才。一個例子是這樣的:

(如AB Udhay建議,它總是更好地以這種方式分裂之前使用TRIM()。)

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); 

    } 

}); 
相關問題