2014-09-19 85 views
0

我需要在WordPress評論框中插入驗證圖片。如果評分是1/5,2/5,3/5,4/5,則應顯示未驗證的圖像,如果評分爲5/5,則應顯示已驗證的圖像。我試了很多版本,但能夠證明只有一個在時間圖像中的所有批註框,如果評級是磨碎機或者小於5如何在WordPress評論部分插入評分圖片?

我的代碼1:

var code = $("<strong>5/5</strong>"); 
code.each(function() { 
    $('p.comment-rating').prepend('<p class="prepen_img"><img src="verified.png" /></p>'); 
}); 

我的代碼2:

if ($("p.comment-rating:contains('2/5')").length !== 0) { 
    $('p.comment-rating').prepend('<p class="prepen_img"><img src="not-verified.png" /></p>'); 
} 
else { 
    $('p.comment-rating').prepend('<p class="prepen_img"><img src="verified.png" /></p>'); 
} 

我的代碼3:

$('p.comment-rating').each(function() { 
    if ($("p.comment-rating:contains('5/5')").length !== 0) { 
     $('p.comment-rating').prepend('<p class="prepen_img"><img src="not-verified.png" /></p>'); 
    } 
    else { 
     $('p.comment-rating').prepend('<p class="prepen_img"><img src="verified.png" /></p>'); 
    } 
}); 

HTML:

<p class="comment-rating"> 
    <img src="2star.gif"> 
    <br> 
    Rating: <strong>2/5</strong> 
</p> 

上面的代碼只顯示一個圖像,else條件不起作用。

+0

能否請你幫誰? – 2014-09-19 09:14:59

+0

你有一個WordPress的評級系統,你想顯示旁邊的「未驗證」或「驗證」的圖像,取決於評級?它是否輸出html,正如你在你的問題中所顯示的:評分:2/5'? – Joonas 2014-09-19 09:30:21

+0

@ Joonas,絕對正確。 2/5是評分系統的輸出。 – 2014-09-19 09:31:52

回答

1

因此,像這樣可以工作:

jsfiddle Demo

HTML:

<p class="comment-rating"> 
    Rating: <strong>2/5</strong> 
</p> 

<p class="comment-rating"> 
    Rating: <strong>5/5</strong> 
</p> 

<p class="comment-rating"> 
    Rating: <strong>1/5</strong> 
</p> 

的jQuery:

$(function() { 

    $('.comment-rating').each(function() { 

     var $this = $(this), 
      // Finds the first number inside '.comment-rating strong' before the forward slash and converts it to a number. 
      rating = parseInt($this.find('strong').text().split('/')[0]); 

     var verify = rating === 5 ? 'Verified' : 'Not-verified'; 

     $this.append('<span>'+ verify +'</span>'); 

    }); 

}); 

我想通文本示例會更清楚,因爲我沒有這樣的圖像,但在這裏是用圖片,在這裏我改線9和第11行稍微同樣的事情:

jsfiddle Demo

同HTML。

的jQuery:

$(function() { 

    $('.comment-rating').each(function() { 

     var $this = $(this), 
      // Finds the first number inside '.comment-rating strong' before the forward slash and converts it to a number. 
      rating = parseInt($this.find('strong').text().split('/')[0]); 

     var verify = rating === 5 ? 'http://placekitten.com/g/20/30' : 'http://placekitten.com/20/30'; 

     $this.append('<img src="'+ verify +'" />'); 

    }); 

}); 
+0

哇..你真了不起!難以置信!。你做了一個魔術!它的工作很好。許多許多感謝最親愛Jonnas ..再次感謝..你能解釋爲什麼我的代碼不工作? – 2014-09-19 12:51:41

+0

@KevinJohn是的,我真的不知道爲什麼我放棄了你的代碼。無論如何,這個問題源於[你在'.each()'函數]中沒有使用'$(this)'(http://jsfiddle.net/f52vp0zj/4/)。對於我的生活,我似乎無法用簡單的術語來解釋這一點,所以我只希望你能夠使用'console.log();'並使用例如chrome開發工具控制檯來查看它給出的值。例如。 'console.log($(this));''和'console.log($('。comment-rating'));' – Joonas 2014-09-19 15:27:50

+0

感謝您的解釋和建議 – 2014-09-20 07:21:14