2014-09-19 82 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