You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML的<script>标签中使用JSON数据填充<img>标签的src属性?为何点语法访问JSON数据无效?

Fixing JSON Data to Image src in HTML

Hey, let's work through your two issues step by step — I spotted a couple of key problems in your code that are preventing your JSON data from populating the <img> tag correctly:

1. The Script Tag Conflict

Your <script> tag has both a src="./index.js" attribute and internal code defining the data object. When a script tag has a src attribute, browsers ignore any code written inside the tag itself. That means your data variable was never actually being defined in the first place!

2. Hardcoded "Variable" in src Attribute

You tried setting src="data.images[0].image", but browsers treat this as a literal string path (it's trying to load a file named data.images[0].image instead of reading the variable value).


Solution 1: Inline Script Setup (No External JS)

Let's separate the data definition and DOM manipulation into proper script tags, and add an ID to your image so we can target it easily:

<!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" />
    <title>Slider</title>
</head>
<body>
    <div class="sliderContainer">
        <!-- Add an ID to target this image -->
        <img id="sliderImage" alt="example" />
    </div>

    <!-- First script: Define your JSON data -->
    <script>
        const data = {
            images: [
                { ID: 0, name: 'name1', image: 'images/example1.jpg', link:'#' },
                { ID: 1, name: 'name2', image: 'images/example2.jpg', link:'#' },
            ],
        };
    </script>

    <!-- Second script: Manipulate the DOM to set the image src -->
    <script>
        // Grab the image element by its ID
        const sliderImage = document.getElementById('sliderImage');
        
        // Now your dot notation will work! Assign the src value from your data
        sliderImage.src = data.images[0].image;
        // Bonus: Set the alt text from your data too
        sliderImage.alt = data.images[0].name;
    </script>
</body>
</html>

Solution 2: Using an External JS File (index.js)

If you want to keep your code in an external file, move all the data and DOM logic into index.js, and make sure to wait for the DOM to fully load before manipulating elements:

HTML File

<!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" />
    <title>Slider</title>
</head>
<body>
    <div class="sliderContainer">
        <img id="sliderImage" alt="example" />
    </div>

    <!-- Only load the external JS file -->
    <script src="./index.js"></script>
</body>
</html>

index.js File

// Define your data
const data = {
    images: [
        { ID: 0, name: 'name1', image: 'images/example1.jpg', link:'#' },
        { ID: 1, name: 'name2', image: 'images/example2.jpg', link:'#' },
    ],
};

// Wait for the DOM to be fully loaded before accessing elements
document.addEventListener('DOMContentLoaded', () => {
    const sliderImage = document.getElementById('sliderImage');
    sliderImage.src = data.images[0].image;
    sliderImage.alt = data.images[0].name;
});

Bonus: Populate Multiple Images

If you want to load all images from your data array instead of just the first one, you can loop through the array and create image elements dynamically:

document.addEventListener('DOMContentLoaded', () => {
    const sliderContainer = document.querySelector('.sliderContainer');
    
    data.images.forEach(imgData => {
        const newImg = document.createElement('img');
        newImg.src = imgData.image;
        newImg.alt = imgData.name;
        sliderContainer.appendChild(newImg);
    });
});

内容的提问来源于stack exchange,提问作者Yogev Batito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 07:02:47