Jquery .append和链接

时间:2014-10-11 12:42:14

标签: javascript jquery

function (data) {
    var json = data;

    if (json["type"] == "story") {
        $(".title").append("<p><a href=" + json["url"] + ">" + json["title"] + "</a> " + json["id"] + "</p>");
    }
}

当我这样做时,我想得到的就是

<p><a href="http://www.vanityfair.com/business/2014/11/satya-nadella-bill-gates-steve-ballmer-microsoft.print">The Microsoft Empire Reboots</a> 8441095</p>

但在某些情况下我得到

<p><a href="https://firstlook.org/theintercept/2014/10/10/core-secrets"></a>Core Secrets: NSA Saboteurs in China and Germany 8441055</p>
<。> .json来自:https://hacker-news.firebaseio.com/v0/item/8441055.json?print=pretty

{
  "by" : "patrickgokey",
  "id" : 8441055,
  "kids" : [ 8441399, 8441097, 8441985, 8441301, 8441852, 8441578, 8441287, 8441389, 8441586, 8441583, 8441584, 8441449, 8441380 ],
  "score" : 161,
  "text" : "",
  "time" : 1412995787,
  "title" : "Core Secrets: NSA Saboteurs in China and Germany",
  "type" : "story",
  "url" : "https://firstlook.org/theintercept/2014/10/10/core-secrets/"
}

这是由.append函数中的错误引起的吗?

1 个答案:

答案 0 :(得分:1)

您需要href属性上的引号:

if (json["type"] == "story") {
    $(".title").append("<p><a href='" + json["url"] + "'>" + json["title"] + "</a> " + json["id"] + "</p>");
}

http://jsfiddle.net/pjammox5/1/

要了解原因,请查看网址的差异:

  

http://www.vanityfair.com/business/2014/11/satya-nadella-bill-gates-steve-ballmer-microsoft.print   https://firstlook.org/theintercept/2014/10/10/core-secrets/

请注意,第二个结尾-secrets/<a href=>结合为自动关闭:

<a href=https://firstlook.org/theintercept/2014/10/10/core-secrets/> <--Closes the tag