我有一些JSON数据,其中包含三项:kicker、headline和link.我将kicker和headline以及一些JS插入到指定的HTML标记中,这些标记包含一个名为placeholder_1
的变量,末尾的数字加1(placeholder_2
、placeholder_3
、placeholder_4
)。
var jsonData = [{
"kicker": "Turkey",
"headline": "Hatay hit by new 6.4-magnitude earthquake",
"link": "https://www.theguardian.com/world/2023/feb/20/turkey-new-6-point-4-magnitude-earthquake-hatay",
},
{
"kicker": "Israel",
"headline": "Benjamin Netanyahu accuses protesters of ‘trampling democracy’",
"link": "https://www.theguardian.com/world/2023/feb/20/israel-benjamin-netanyahu-accuses-protesters-of-trampling-democracy",
},
{
"kicker": "Live",
"headline": "Russia-Ukraine war: Joe Biden’s surprise visit to Kyiv ‘unprecedented in modern times’, says US",
"link": "https://www.theguardian.com/world/live/2023/feb/20/russia-ukraine-war-live-updates-latest-news-foreign-ministers-eu-ammunition-deal",
},
{
"kicker": "Folly of Gossip",
"headline": "A look into Sydney’s early drag scene",
"link": "https://www.theguardian.com/artanddesign/gallery/2023/feb/20/folly-of-gossip-a-look-into-sydneys-early-drag-scene-in-pictures"
}
]
$(document).ready(function() {
var k = 1;
//loop through json data and insert into corresponding divs
for (var i = 0; i < jsonData.length; i++) {
document.getElementById("placeholder_" + (k)).innerText = jsonData[i].kicker;
document.getElementById("placeholder_" + (k = k + 1)).innerText = jsonData[i].headline;
document.getElementById("placeholder_" + (k = k + 1)).href = jsonData[i].link;
k = k + 1;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<section>
<div class="headlines">
<div class="section-title">
<h1 class="opinion-kk">Opinion</h1>
</div>
<div class="articles main-stories">
<img src="https://picsum.photos/300/200?random=1">
<div>
<p class="main-title">placeholder_1 / <a href="placeholder_3">placeholder_2</a></p>
<p class="mainPara">Temporibus et repudiandae neque.</p>
</div>
class="sub-title"><strong>Et /</strong> <a href="#">Consectetur debitis non et amet eum</a></p>
</div>
<div class="articles secondary-stories add-subtitle">
<img src="https://picsum.photos/300/200?random=2">
<p class="secondary-title"><strong>placeholder_4 /</strong> <a href="placeholder_6">placeholder_5</a></p>
<p class="sub-title"><strong>Ut /</strong> <a href="#">Quia tempora iste sed dolorem</a></p>
</div>
<div class="articles secondary-stories">
<img src="./assets/img/s_493.jpg">
<p><strong>placeholder_7 /</strong> <a href="placeholder_9">placeholder_8</a></p>
</div>
</div>
</section>
</header>
但是我没有以正确的方式在href标记中插入链接。
1条答案
按热度按时间q5lcpyga1#
问题是代码中的这些占位符不是id,而是简单的文本。我改变了它(对于内容和href属性,链接只使用1个id),现在它可以完美地工作了: