如何使用Javascript动态生成面包屑模式?

如何使用Javascript动态生成面包屑模式?,javascript,html,schema.org,json-ld,structured-data,Javascript,Html,Schema.org,Json Ld,Structured Data,下面是实际用于显示每页面包屑的HTML <c:forEach items="${breadcrumbArray}" var="breadcrumb" varStatus="loopCounter"> <c:if test="${breadcrumb ne 'store'}"> <li clas

下面是实际用于显示每页面包屑的HTML

            <c:forEach items="${breadcrumbArray}" var="breadcrumb" varStatus="loopCounter">
                <c:if test="${breadcrumb ne 'store'}">
                    <li class="breadcrumb__item">
                        <c:choose>
                            <c:when test="${not loopCounter.last}">                                    
                                <a href="/${breadcrumb}">${breadcrumb}</a>                             
                            </c:when>
                            <c:otherwise>
                                ${fn:replace(breadcrumb, '-', ' ')}
                            </c:otherwise>
                        </c:choose>
                    </li>
                </c:if>
            </c:forEach>

  • ${fn:replace(面包屑,'-','')}
  • 用于动态生成架构的Javascript

    <script type="text/javascript">
        $(document).ready(function(){
           var el = document.createElement('script');
    
           el.type = 'application/ld+json';
           el.text = JSON.stringify({ "@context": "https://schema.org/",
                                      "@type": "BreadcrumbList",
                                      "itemListElement": [{
                                          "@type": "ListItem",
                                          "position": 1,
                                          "name": "",
                                          "item": ""                                     
                                      }]
                                 });
    
           document.querySelector('head').appendChild(el);
        });
    </script>
    
    
    $(文档).ready(函数(){
    var el=document.createElement('script');
    el.type='application/ld+json';
    el.text=JSON.stringify({“@context”:”https://schema.org/",
    “@type”:“面包屑列表”,
    “itemListElement”:[{
    “@type”:“ListItem”,
    "立场":一,,
    “名称”:“,
    “项目”:”
    }]
    });
    document.querySelector(“head”).appendChild(el);
    });
    
    例如“家>我们的任务>我们是谁”的模式应该像这样生成:

    <script type="application/ld+json">
    {
        "@context": "https://schema.org/",
        "@type": "BreadcrumbList",
        "itemListElement": [{
            "@type": "ListItem",
            "position": 1,
            "name": "Home",
            "item": "https://corp.com/"
            },{
            "@type": "ListItem",
            "position": 2,
            "name": "Our Mission",
            "item": "https://corp.com/our-mission/"
            },{
            "@type": "ListItem",
            "position": 3,
            "name": "Who We Are",
            "item": "https://corp.com/our-mission/who-we-are"
        }]
    }
    </script>
    
    
    {
    “@context”:”https://schema.org/",
    “@type”:“面包屑列表”,
    “itemListElement”:[{
    “@type”:“ListItem”,
    "立场":一,,
    “姓名”:“家”,
    “项目”:https://corp.com/"
    },{
    “@type”:“ListItem”,
    "立场":二,,
    “名称”:“我们的使命”,
    “项目”:https://corp.com/our-mission/"
    },{
    “@type”:“ListItem”,
    “立场”:3,
    “姓名”:“我们是谁”,
    “项目”:https://corp.com/our-mission/who-we-are"
    }]
    }
    

    脚本未附加到“head”标记。

    此脚本有几部分

    第一:脚本未附加到'head'标记 这可能需要更多信息,代码中的内容至少应该在
    头中呈现JSON-LD
    脚本
    标记。您的环境中可能发生了一些事情,阻止您向
    头部写入代码。您可以尝试将代码更改为以下内容:

    document.head.appendChild(el)
    document.getElementsByTagName('head')[0]。appendChild(el)
    (如果需要支持较旧的浏览器)

    更多信息可在以下SO线程中找到:

    我再次怀疑这是否是问题所在。我也会尝试在页面的其他地方呈现
    脚本
    ,而不是
    标题
    ,看看这是否适合您(同样相关的,请参阅我在回答末尾的最后一个注释)

    第二:使用JavaScript创建JSON-LD 以下是一个粗略的、不使用jQuery但与ES5兼容的解决方案,可以帮助您生成:

    HTML
    
    
  • JavaScript
    //创建脚本
    var el=document.createElement('script');
    el.type='application/ld+json';
    //设置初始位置
    var位置=0;
    //创建面包屑对象
    变量面包屑={
    位置:0,
    姓名:“,
    项目:“
    }
    //列表项的空数组
    var listary=[]
    //循环遍历每个面包屑链接并设置属性
    var items=document.querySelectorAll('.breadcrumb link');
    对于(变量i=0;i

    第三:你真的想这样做吗? 正如一位评论员提到的,用JavaScript写出JSON-LD可能是个问题。如果你的意图与搜索引擎优化相关,你可能想稳操胜券,并呈现这个服务器端。不能保证搜索引擎机器人会捕捉到客户端呈现的类似内容

    更新:,但这可能仍然是其他搜索引擎的问题。我也喜欢犯谨慎的错误。谢谢@JayGray

    如果您必须硬编码JSON-LD的值,正如评论员提到的,您可以使用仍然受支持的RDFa(即使与JSON-LD相比不是首选)。根据您的代码动态呈现HTML。下面是一个示例,它显示了以下内容:

    
    
  • (请记住,RDFa和微数据——与JSON-LD不同——如果动态生成,则不会被搜索引擎获取)

    最后说明: 即使建议JSON-LD位于
    头部
    ,它也不需要位于头部,以便拾取p
    <ol class="breadcrumbs">
        <li class="breadcrumb-item">
            <a class="breadcrumb-link" href="https://mypage.com/page1">Page 1</a>
        </li>
        <li class="breadcrumb-item">
            <a class="breadcrumb-link" href="https://mypage.com/page2">Page 2</a>
        </li>
        <li class="breadcrumb-item">
            <a class="breadcrumb-link" href="https://mypage.com/page3">Page 3</a>
        </li>
    </ol>
    <!-- Testing Purposes -->
    <div class="output"></div>
    
    // Create Script
    var el = document.createElement('script');
    el.type = 'application/ld+json';
    
    // Set initial position
    var position = 0;
    
    // Create breadcrumb object
    var breadcrumb = {
        position:0,
        name:"",
        item:""
    }
    
    // Empty array for list items
    var listArray = []
    
    // Loop through each breadcrumb link and set attributes
    var items = document.querySelectorAll('.breadcrumb-link');
    for(var i = 0; i < items.length; i++) {
        var newItem = Object.create(breadcrumb);
        var curItem = items[i];
    
        newItem["@type"] = "ListItem";
        position++;
        newItem.position = position;
        newItem.name = curItem.text;
        newItem.item = curItem.getAttribute('href');
        listArray.push(newItem);
    }
    
    // Create overarching Schema object
    var breadcrumbSchema = {
        "@context": "https://schema.org/",
        "@type": "BreadcrumbList",
        "itemListElement": listArray
    };
    
    // Stringify JSON
    var finalSchema = JSON.stringify(breadcrumbSchema);
    
    // Add schema to Script
    el.text = finalSchema;
    
    // Set head variable with browser fallback
    var head = document.head || document.getElementsByTagName("head")[0];
    
    // Add to head (This won't work in codepen)
    head.appendChild(el);
    
    // Testing purposes - Show example of string in HTML
    document.querySelector('.output').innerHTML = finalSchema;
    
    // Testing purposes - Inspect source to see script generated inside of the "output" div
    document.querySelector('.output').appendChild(el);
    
    <ol vocab="https://schema.org/" typeof="BreadcrumbList">
        <li property="itemListElement" typeof="ListItem">
            <a property="item" typeof="WebPage" href="https://example.com/dresses">
                <span property="name">Dresses</span>
            </a>
            <meta property="position" content="1">
        </li>
        <li property="itemListElement" typeof="ListItem">
            <a property="item" typeof="WebPage" href="https://example.com/dresses/real">
                <span property="name">Real Dresses</span>
            </a>
            <meta property="position" content="2">
        </li>
    </ol>
    
    <script type="application/ld+json">
    {
    "@context": "https://schema.org/",
    "@type": "BreadcrumbList",
    "itemListElement": [
        {
        "@type": "ListItem",
        "position": 1
        "name": "Home",
        "item": "${baseURL}",
        },
        <c:forEach items="${breadcrumbArray}" var="breadcrumb" varStatus="loopCounter">
        {
        "@type": "ListItem",
        "position": ${loopCounter.index+1}
        "name": "${fn:replace(breadcrumb, '-', ' ')}",
        "item": "${baseURL}${breadcrumbArray[loopCounter.index-1]}/${breadcrumb}",
        }
        </c:forEach>
        ]
    }
    </script>