更正语法以创建<a> tag with JQuery

时间:2016-10-19 17:39:11

标签: jquery

I'm working with the Wikipedia API and I'm trying to display the result of JSON data. My first two elements work and they display the data correctly:

var link = $("<a href=</a>")
var newEl = $("<li></li>");
var newParagraph1 = $("<p></p>");
var newParagraph2 = $("<p></p>");
var list = $("#list");

 list.append(newEl);
    newEl.text(data[1][0]);
    newEl.append(newParagraph1.text(data[2][0]));

For the third element I want a simple clickable link to the Wikipedia page that is giving me that information, something like:

   newEl.append(newParagraph2.append("<a href =" + data[3][0] + ">" + " </a>"));

But it's not working. If I change "newParagraph2.append" for "newParagraph2.text", then I do get the text but everything is turned into a string I assume, not an actual tag. What is the correct way to create an tag, insert the "data[3][0]" after the href= and close the tag?

2 个答案:

答案 0 :(得分:3)

看起来你只是缺少内部引号和一些文字:

newEl.append(newParagraph2.append('<a href ="' + data[3][0] + '">' + 'Some Clickable Text</a>'));

另外,如果您没有使用它,请删除link变量。如果您正在使用它,请将其更改为

var link = $("<a></a>")

答案 1 :(得分:2)

目前的方法是缺少所需链接的双引号,请参阅下面的修改后的代码段:

newEl.append(newParagraph2.append('<a href="' + data[3][0] + '">' + ' </a>'));