【问题标题】:how to append a hyperlink from a json file to html如何将超链接从 json 文件附加到 html
【发布时间】:2016-11-20 09:40:45
【问题描述】:

我正在使用 jQuery 来解析和显示 JSON 文件中的数据。我在浏览器中吐出所有内容,但我的 JSON 文件中的一个键有一个 url 作为值。我试图让它显示为一个链接,但它一直给我一个错误。

这是我的 json:

{
  "website" : {
    "url" : "http://www.stuffinmagazines.com"
  },
  "phone1" : "222-444-4853",
  "business" : "Stuff Inc."
}

还有我的 jQuery:

$.getJSON('data.json', function(data) {
        var output = '<ul class="searchresults">';
        $.each(data, function(key, val) {
            if (val.item.search(myExp) != -1) {
                output += '<li>';
                output += '<p>' + "Website: " + '<a href = ' + val.website.url + '>' + URL + '</a>' + '</p>';
                output += '<p>' + "Phone: " + val.phone + '</p>';
                output += '<p>' + "Business: " + val.business + '</p>';
                output += '</li>';
            }
        });
        output += '</ul>';
        $('#update').html(output);

我想我没有正确放置 val.website.url...有人知道如何从 json 文件中检索 url 吗?

【问题讨论】:

  • &lt;a href = "' + val.website.url + '"&gt;URL&lt;/a&gt;'
  • 没有工作请解释你的答案:)
  • 错误信息是什么?
  • script.js:12 Uncaught TypeError: Cannot read property 'url' of undefined
  • 这意味着在其中一个文件中未定义“网站”,而不是“网址”。

标签: javascript jquery json url hyperlink


【解决方案1】:

你缺少双引号试试下面 '&lt;a href = "' + val.website.url + '"&gt;URL&lt;/a&gt;'

【讨论】:

    【解决方案2】:

    这部分看起来不对:

    '<a href = ' + val.website.url + '</a>'
    

    假设val.website.url 有网址,那位应该是:

    '<a href = "' + val.website.url + '"></a>'
    

    我们可以像这样构建&lt;a&gt; 元素:

    <div id="myDiv">A place to put the link<div>
    
    <script>
      // not using http: in url makes it work for both http: & https: 
      var url = "//jsfiddle.net";
    
      var el = $("<a />"); // a virtual <a> element
    
      // put url and some text to click on into our virtual element
      el.prop('href',url).text('click here'); 
    
      $("#myDiv").html(el); // put the element into the page
    </script>
    

    click here for the jsfiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2016-06-18
      • 1970-01-01
      • 2012-04-01
      • 2012-11-24
      相关资源
      最近更新 更多