如何获取元标记内容值并将其取平均值

时间:2019-03-08 20:24:46

标签: javascript html5 meta-tags schema.org structured-data

我正在一个使用Schema.org微数据获取结构化内容产品列表的网站上工作,显然Google要求对所有评论进行综合评分。我怎样才能抓住所有 <meta itemprop="ratingValue" content="#" /> 标签,然后将它们平均化为变量,然后输出到:

<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
  <meta itemprop="ratingValue" content="average #" />
  <meta itemprop="reviewCount" content="# reviews" />
</div> 

使用JQuery或JavaScript? (其中#=额定值)

2 个答案:

答案 0 :(得分:2)

是的,使用jQuery并不是很难。该代码将获取所有元内容,将它们转换为整数,找到平均评级,然后在HTML元素的底部附加一些head

// first gather all the meta elements with an itemprop value of "ratingValue"
var metas = $('meta[itemprop="ratingValue"]').get();

// convert the content values of these elements to integers and put them in an array
var ratings = metas.map((m) => ~~m.content);

// calculate and round the average rating value
var average = ~~(ratings.reduce((a,b) => a + b) / ratings.length + 0.5);

// create the HTML for the aggregateRating parent div
var aggregateRating = '<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">';

// create ratingValue meta HTML using the average rating
var ratingValue = '<meta itemprop="ratingValue" content="average ' + average + '" />';

// create aggregateRating meta HTML using the rating count
var reviewCount = '<meta itemprop="reviewCount" content="' + ratings.length + ' reviews" />';

// combine these strings and a closing tag, then append the HTML to the end of head
$('head').append(aggregateRating + ratingValue + reviewCount + '</div>');

或者您甚至可以使用Bernard方法

$('head').append(['<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">', '</div>'].join([
  ['ratingValue', 'average ' + ~~((r = $('meta[itemprop="ratingValue"]').get().map((m) => ~~m.content)).reduce((a, b) => a + b) / r.length + .5)],
  ['reviewCount', r.length + ' reviews']
].map((a, b) => ['<meta itemprop="', '" content="', '">'].map((c, d) => [c, a[d]]))).replace(/,/g, ''));

答案 1 :(得分:1)

var aggregates = document.querySelectorAll("[itemprop='aggregateRating'");
var scores = 0;
var n = 0;

for (var i = 0; i < aggregates.length; i++) {
  scoreCurr = parseFloat(aggregates[i].querySelector("[itemprop='ratingValue']").getAttribute("content"));
  nCurr = parseFloat(aggregates[i].querySelector("[itemprop='reviewCount']").getAttribute("content"));
  scores += scoreCurr;
  n += nCurr;
}

alert(scores/n);
<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
  <meta itemprop="ratingValue" content="35" />
  <meta itemprop="reviewCount" content="7" />
</div>

<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
  <meta itemprop="ratingValue" content="42" />
  <meta itemprop="reviewCount" content="10" />
</div>