javascript - 如何获取元标记内容值并对其求平均值

标签 javascript html 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? (其中 # = 评级值)

最佳答案

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

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

或者你甚至可以使用伯纳德方法

$('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, ''));

关于javascript - 如何获取元标记内容值并对其求平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55070511/

相关文章:

html - 链接标签填充整个屏幕

css - 当屏幕宽度为 "is too small or too big"时,条件视口(viewport)缩放以适合?

javascript - 当我点击其他地方时如何隐藏我的滑动sidenav?

JavaScript 从用户输入中查找平均值

c# - 如何使用 ASP.NET 设置数据属性?

html - 在 META TITLE 标签中重复 TITLE 文本有什么好处吗?

facebook - 如何设置 Metatag fb :pages correctly to enable link editing for one page with multiple channels?

java - 在 Java 中使用 IE/Chrome HTML-Renderer 或使用 JavaScript 存储文件

javascript - 导航栏元素不折叠

javascript - CSS :hover effect on current and previous elements