【问题标题】:How to get the src attribute from a JSON object? [duplicate]如何从 JSON 对象中获取 src 属性? [复制]
【发布时间】:2020-05-20 14:09:15
【问题描述】:

这是我的 JSON 的一个对象:

        {
          "box": [
            {
              "htm": "<div style=\"float:left;margin:0 0 10px\"><img alt=\"BICYCLE GARAGE\" src=\"//cdn.membershipworks.com/u/5ceef04cf033bfad7c9d9c82_lgl.jpg?1565140260\" class=\"SFbizlgo\" onerror=\"SF.del(this)\"></div><div style=\"float:left\"><h1 style=\"display:block;margin:0;padding:0;\">BICYCLE GARAGE</h1><p style=\"margin:15px 0 0;\">&quot;For bicycling around the block or around the world&quot; Bloomington, Indiana</p></div><div style=\"clear:both;\"></div>"
            }
          ],
          "lbl": "About"
        }
      ],

为了得到我所做的盒子对象 const logoHtml = tpl[0].box[0].htm 在我的控制台中,我收到了&lt;div style="float:left;margin:0 0 10px"&gt;&lt;img alt="ALAMEDA BICYCLE" src="//cdn.membershipworks.com/u/5ceef04bf033bfad7c9d9c0a_lgl.jpg?1566946141" class="SFbizlgo" onerror="SF.del(this)"&gt;&lt;/div&gt;&lt;div style="float:left"&gt;&lt;h1 style="display:block;margin:0;padding:0;"&gt;ALAMEDA BICYCLE&lt;/h1&gt;&lt;p style="margin:15px 0 0;"&gt;&lt;/p&gt;&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;

哪个好!为了获得我一直在做的 src 属性const newLogo = document.getElementsByTagName('img').src

现在,如何结合这两个常量来从 img 标签中获取 src 属性?

【问题讨论】:

  • ^ 解析页面 sn-p 使用 document.createElement("div") 而不是 document.createElement("html")。

标签: javascript html arrays json reactjs


【解决方案1】:

我已经使用您的描述编写了一个示例。希望对您有所帮助。

var htmlObj = {
          "box": [
            {
              "htm": "<div style=\"float:left;margin:0 0 10px\"><img alt=\"BICYCLE GARAGE\" src=\"//cdn.membershipworks.com/u/5ceef04cf033bfad7c9d9c82_lgl.jpg?1565140260\" class=\"SFbizlgo\" onerror=\"SF.del(this)\"></div><div style=\"float:left\"><h1 style=\"display:block;margin:0;padding:0;\">BICYCLE GARAGE</h1><p style=\"margin:15px 0 0;\">&quot;For bicycling around the block or around the world&quot; Bloomington, Indiana</p></div><div style=\"clear:both;\"></div>"
            }
          ],
          "lbl": "About"
        };

//Parse the string into a dom elements
var elem = new DOMParser().parseFromString(htmlObj.box[0].htm, 'text/html');
//The image
var img = elem.getElementsByTagName('img');
// Get the src.
document.getElementById('mysource').innerHTML = img[0].src;
&lt;div id="mysource"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 2023-04-03
    • 2018-06-08
    • 1970-01-01
    • 2011-09-08
    • 2019-04-19
    • 1970-01-01
    相关资源
    最近更新 更多