首页 > 解决方案 > 如何在此面包屑模式 JSON 生成器中显示位置编号

问题描述

请看一下这是我正在使用的代码:


<div id="app">
  <h1>FAQPage Schema Form</h1>
  <p>Add all your Questions and answers</p>
  <div class="border" v-for="(field, index) in itemListElement">
    <button class="removeBtn" @click="RemoveField(index)">
    X
  </button>
    <textarea v-model="field.name" placeholder="PAGE NAME"></textarea><br/>
    <textarea v-model="field.item" placeholder="URL"></textarea><br/>
    </div>
  <button class="addBtn" @click="AddField">
    Add a Question
  </button>

  <h2>JSON Output</h2>
  <p>After adding all your questions, add this code to your FAQ page</p>
  <textarea id="codeArea">
  &lt;script type="application/ld+json"&gt;
  {{$data | json }}
  &lt;/script&gt;
  </textarea>
  <div class="tooltip">
    <button class="copyCode" onclick="copyFunction()" onmouseout="outFunc()">
<span class="tooltiptext" id="myTooltip">Copy to clipboard</span>
Copy Code</button>
  </div>
</div>

这是脚本

function copyFunction() {
  var copyText = document.getElementById("codeArea");
  copyText.select();
  document.execCommand("copy");
  var tooltip = document.getElementById("myTooltip");
  tooltip.innerHTML = "Copied code!";
}

function outFunc() {
  var tooltip = document.getElementById("myTooltip");
  tooltip.innerHTML = "Copy to clipboard";
}
//Begin Vue Code
new Vue({
  el: "#app",
  data: {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: []
  },
  created: function() {
    this.mainEntity.push({
      "@type": "Question",
      name: "",
      acceptedAnswer: { "@type": "Answer", text: "" }
    });
  },
  methods: {
    AddField: function() {
      this.mainEntity.push({
        "@type": "Question",
        name: "",
        acceptedAnswer: { "@type": "Answer", text: "" }
      });
    },
    RemoveField(index) {
      this.mainEntity.splice(index, 1);
    }
  }
});

您可以在这里看到它的实际效果: https ://codepen.io/adaprile/pen/orzxgr

当前显示的输出是这样的:(我已经添加了我想要显示数组项的索引号的位置。)

  <script type="application/ld+json">
  {
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
       "position": "WANT TO DISPLAY INDEX NUMBER HERE",
      "name": "",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": ""
      }
    }
  ]
}
  </script>

我可以在这里使用什么代码将数组项的索引显示为位置编号以 1 开头?

标签: javascriptvue.js

解决方案


据我了解,您想将数组元素的索引添加到元素本身。因此,每当您将元素推入数组时,您都可以检查数组长度:

this.mainEntity.push({
        "@type": "Question",
        name: "",
        position: this.mainEntity.length+1,
        acceptedAnswer: { "@type": "Answer", text: "" }
      });

推荐阅读