简体   繁体   English

使用JavaScript将JSON属性值添加到HTML元素的属性值中

[英]Using JavaScript to add a JSON property value into a HTML element's attribute value

I have some "img" properties within a JSON file, which have .jpg file paths as their values (eg "images/image.jpg"). 我在JSON文件中有一些“ img”属性,这些属性以.jpg文件路径作为它们的值(例如“ images / image.jpg”)。

Im trying to add these values into the 'src' attribute of existing HTML elements, the following is what I have tried so far… 我正在尝试将这些值添加到现有HTML元素的'src'属性中,以下是我到目前为止尝试过的内容…

  1. Creating text nodes from the JSON object, then trying to add those as the 'src' attribute values using the '.setAttribute()' method, which results in an object being added instead of the url path as a string. 从JSON对象创建文本节点,然后尝试使用'.setAttribute()'方法将其添加为'src'属性值,这将导致添加一个对象而不是将URL路径作为字符串。

    var img = document.createElement("img"); var img = document.createElement(“ img”); var imgSrc = document.createTextNode(object); var imgSrc = document.createTextNode(object); img.setAttribute(src, imgSrc); img.setAttribute(src,imgSrc);

  2. Using the 'JSON.stringify()' method to convert the JSON values into strings and adding those as the img elements 'src' attribute values. 使用'JSON.stringify()'方法将JSON值转换为字符串,并将其添加为img元素的'src'属性值。 This results in the src attribute being filled with the correct paths, but they are surrounded by %22, presumably representing the quotation marks that surround strings. 这导致src属性填充有正确的路径,但是它们被%22包围,大概表示包围字符串的引号。

    var img = document.createElement("img"); var img = document.createElement(“ img”); var imgSrc = JSON.stringify(object); var imgSrc = JSON.stringify(object); img.setAttribute(src, imgSrc); img.setAttribute(src,imgSrc);

Any ideas on how I can achieve what I'm trying to do? 关于如何实现自己想做的任何想法?

Thanks in advance. 提前致谢。

It sounds like you have a JSON string that has already been parsed into a JavaScript object (or perhaps you're not using JSON at all, and your starting point is the object). 听起来您有一个已被解析为JavaScript对象的JSON字符串(或者您根本就没有使用JSON,而您的起点就是该对象)。 You haven't told us what the JSON is or what the object structure is. 您尚未告诉我们JSON是什么或对象结构是什么。 In a comment below, you gave part of it: 在下面的评论中,您提供了部分内容:

"img": "_/images/image-one.jpg"

...but that would be invalid JSON just on its own. ...但这只是无效的JSON。 I'm going to assume the actual JSON looks like this: 我将假设实际的JSON如下所示:

{
    "img": "_/images/image-one.jpg"
}

...and that it's already been parsed, so we have an object referenced from the variable object that has a property, img , containing the URL for the image. ...并且已经被解析,因此我们有一个从变量object引用的object ,该object具有属性img ,其中包含图像的URL。

To use the img property from that object, you just refer to it: 要使用该对象的img属性,只需引用它:

var img = document.createElement("img");
img.src = object.img;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM