javascript 使div可从JSON单击到动态链接

ar7v8xwq  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(135)

我尝试创建一个包含新闻文章的div,需要使用div将用户发送到JSON文件中提供的链接所引用的新页面。我的问题是如何正确引用JSON文件中的链接,因此当JSON文件更新时,目录也会更新。(目前我还在学习JS)
JSON文件:

{
    "AUD": [
        {
            "title": "Pound Australian Dollar Exchange Rate News: GBP/AUD Rallies on Risk-Averse Market",
            "media": "TorFX News",
            "date": "7 mins ago",
            "link": "https://news.torfx.com/post/2022-12-29_pound-australian-dollar-exchange-rate-news-gbp-aud-rallies-on-risk-averse-market/"
        }
      ]
}

HTML和JS:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <!----======== CSS ======== -->
    <link rel="stylesheet" href="style.css">
    
    
    <link href='https://unpkg.com/boxicons@2.1.1/css/boxicons.min.css' rel='stylesheet'>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" charset="UTF-8"></script>
    
</head>
<body>
    <div class="forex_news_container1">
        <div class="forex_news_containerAUD fxcontentNEWS">
            <div class="yooo" onclick="setCurrentLocation()" style="cursor: pointer;">
                send_to_new_page
            </div>
          
            <script>
                const requestUrl67 = 'https://api.npoint.io/b4841826d7668f639d10';
                const requestJSON67 = async url => {

                  const response67 = await (await fetch(url)).json();
                    function setCurrentLocation() {
                        var newloc = response67.AUD[0].link;
                        window.location.href = newloc;
                    }
                }
                requestJSON67(requestUrl67);
            </script>
        </div>
    </div>

如果我把response67.AUD[0].link;改为实际的链接,那么它就可以正常工作,尽管继续手动输入所有新闻文章的每个链接(有很多,这只是一个片段)并不符合我的最佳利益。

z9smfwbn

z9smfwbn1#

JS不能直接处理JSON,必须使用JSON.parse()函数将JSON解析为JS对象/数组。
你可以换句台词

var newLoc = response67.AUD[0].link;

改为:

var object = JSON.parse(response67);
var newLoc = object.AUD[0].link;
let response = `{
  "AUD": [{
    "title": "Pound Australian Dollar Exchange Rate News: GBP/AUD Rallies on Risk-Averse Market",
    "media": "TorFX News",
    "date": "7 mins ago",
    "link": "https://news.torfx.com/post/2022-12-29_pound-australian-dollar-exchange-rate-news-gbp-aud-rallies-on-risk-averse-market/"
  }]
}`;

response = JSON.parse(response);

console.log(response.AUD[0].link);

相关问题