Jquery .append and links

Jquery .append and links

本文关键字:links and append Jquery      更新时间:2023-09-26
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 函数中的错误引起的吗?

您需要

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