我正在尝试获取元描述,并将其内容复制到某些JSON模式标记中。但是我不确定如何获取它以将变量正确地传递到JSON结构。
这是我的想法:
<script>
const desc = $('meta[name=description]').attr("content");
</script>
<script type='application/ld+json'>
{
"@context": "http://www.schema.org",
"@type": "LocalBusiness",
"name": "BizName",
"telephone": "+1234567890",
"description": "'+desc+'",
....
}
</script>
我知道它不会完全将desc
变量直接传递到JSON标记中,因为它位于单独的脚本标记中。我只是不确定如何将两者结合起来以使其正常工作。希望这是有意义的,并欢迎任何建议。
您不能-它是静态 JSON标记,而不是动态JavaScript。
从技术上讲,您可以动态地使用所有的Schema JSON注入一个全新的<script>
标记,但是软件解析页面中的JSON + LD数据可能不会解释JavaScript *。
首先构建模式,然后将其插入。
<script>
const desc = $('meta[name=description]').attr("content").toString();
var schema = {
"@context": "http://www.schema.org",
"@type": "LocalBusiness",
"name": "BizName",
"telephone": "+1234567890",
"description": desc,
....
}
var script = document.createElement('script');
script.type = "application/ld+json";
script.text = JSON.stringify(schema);
document.querySelector('body').appendChild(script);
</script>