簡體   English   中英

使 div 可點擊到來自 JSON 的動態鏈接

[英]Make a div clickable to dynamic link from JSON

我正在嘗試創建一個包含新聞文章的 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 & 記者:

<!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; 到實際鏈接,然后它工作正常。 盡管手動輸入所有新聞文章的每個鏈接並不符合我的最佳利益(有很多,這只是一個片段)。

JS 不能直接使用 JSON。您必須使用JSON.parse() function 將 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM