在使用API时,徘徊如何将动态变化的href
添加到附加的<a>
元素。它就行了
$("#list").append($("<a href='data[3][0]'><li></li></a>").text(data[1][0]));
data[3][0]
从wiki API中提供了诸如“https://en.wikipedia.org/wiki/China”之类的站点名称,但不起作用。添加例如“https://www.google.com”到href
工作正常。我想解决方案可能是事先将data[3][0]
改为实际值,但我不知道该怎么做。
var title = document.querySelector("#title");
var description = document.querySelector("#description");
var link = document.querySelector("#link");
var myData = {}
$("#search").keyup(function(e){
var searchTerm = this.value;
if(e.which == 13) {
$.ajax({
url: 'https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=' + searchTerm,
data: myData,
type: 'GET',
dataType: 'jsonp',
headers: { 'Api-User-Agent': 'Example/1.0' },
success: function(data) {
$("#list").append($("<a href='data[3][0]'><li></li></a>").text(data[1][0]));
$("#list").append($("<li></li>").text(data[2][0]));
}
});
};
});
提前致谢。
试试这个
$("#list").append($("<a href='"+data[3][0]+"'><li></li></a>").text(data[1][0]));
字符串连接很快就会变得很麻烦。幸运的是,从1.4开始,jQuery带有一个简单的函数签名:
jQuery(html,attributes) html:输入:htmlString。定义单个独立HTML元素的字符串 attributes:类型:PlainObject。调用新创建的元素的属性,事件和方法的对象。
适用于您的代码的内容包括:
$('<a><li/></a>', {href: data[3][0]})
.appendTo(document.querySelector("#list"))
.text(data[1][0])
可是等等 .. !锚<a>
标签不应包含<li>
元素作为直接孩子。 The HTML <li> (…) must be contained in a parent element: an ordered list (<ol>), an unordered list (<ul>), or a menu (<menu>)
$('<li><a/></li>').appendTo(document.querySelector("#list"))
.find('a').attr('href',data[3][0]).text(data[1][0])
let data = ['http://nowhere.com', 'Nowhere'];
document.querySelector('button').addEventListener('click', e => {
$('<li><a/></li>')
.appendTo(document.querySelector("#list"))
.find('a').attr('href',data[0]).text(data[0])
})
li, a{color: black}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list"></ul>
<button>Add item to list</button>