如何将json文件中的超链接附加到html中

how to append a hyperlink from a json file to html

本文关键字:html 超链接 json 文件      更新时间:2023-09-26

我使用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吗?

这部分看起来不对:

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

假设val.website.url具有url,那么该位应该是:

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

我们可以这样构建<a>元素:

<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>

点击这里获取jsfiddle

您缺少双引号,请尝试以下操作'<a href = "' + val.website.url + '">URL</a>'