2013-05-22 55 views
0

如果在LI中存在特定文本並相應地添加一個類,則需要使用jQuery進行檢查。檢查某些文本並添加類

東西沿着這些路線...

if ($('ul li:last-child:contains("this text")').length > 0) { 
    $(this).addClass("this"); 
} else if ($('ul li:last-child:contains("that text")').length > 0) 
    $(this).addClass("that"); 
} 

顯然,上面的代碼不工作,但希望它是接近到什麼,我需要。任何人都知道我該怎麼寫呢?

編輯: 這裏是感謝的是爲我工作,以低於adeneo的回答確切的代碼...

$('.job-result .job-details ul li:last-child').addClass(function() { 
    return $(this).text().indexOf('Augusta') != -1 ? 'augusta' : 
      $(this).text().indexOf('Aiken') != -1 ? 'aiken' : 
      $(this).text().indexOf('Job') != -1 ? 'jobshop' : ''; 
}); 
+0

你可以設置提琴手? – Amit

+0

顯示你的html。 –

+0

'$(this)'是指什麼? –

回答

5

你在做什麼,如果通過使用長度存在一個元素被檢查,如果確實如此'nt存在,請向該元素添加一個類?這不會工作,因爲元素不存在,並且在if/else這樣的條件下沒有特殊的作用域,所以this沒有意義?

如何只使用內部addClass()一個匿名函數來獲取範圍和檢查內容:

$('ul li:last-child').addClass(function() { 
    return $(this).text().indexOf('this text') != -1 ? 'this' : 
      $(this).text().indexOf('that text') != -1 ? 'that' : ''; 
}); 
+0

這工作正是我需要它。感謝您對邏輯的返工。我在我的問題中加入了確切的用法,以幫助其他人。 – Sean