[英]appendTo shows strange behaviour
What I am trying to do (for now) is query the Wikipedia API with a search string, 我现在想要做的是使用搜索字符串查询Wikipedia API,
$(document).ready(function() {
$(".search").on("click", getArticles);
function getArticles() {
var searchTerm = $("#wiki-search").val().trim();
console.log(searchTerm);
var url = "http://en.wikipedia.org//w/api.php?callback=?";
$.getJSON(url, {
action: "query",
format: "json",
list: "search",
srprop: "snippet",
srlimit: 10,
srsearch: searchTerm
}, displayArticles);
and from the returned JSON object, display the value of a particular property ( snippet
in this case) by appending it to a div element: 并从返回的JSON对象中,将特定属性的值(在本例中为snippet
)附加到div元素上,以显示该属性:
function displayArticles(wikiJSON) {
if(wikiJSON.query.searchinfo.totalhits === 0) {
// resultsDiv.innerHTML = "No results found";
$("<h3>No results Found</h3>").appendTo("#resultsID");
}
else {
$(wikiJSON.query.search[0].snippet).appendTo("#resultsID");
}
But as seen in this pen , the snippet value is flashed momentarily on the screen and is gone. 但是正如这支笔所见,摘要值在屏幕上短暂闪烁并消失了。 Could anyone please explain what's going wrong with my code? 谁能解释我的代码出了什么问题?
HTML: HTML:
<form role="form">
<div class="input-group">
<input class="form-control" id="wiki-search" type="text" placeholder="Enter search string...">
<span class="input-group-btn">
<button class = "btn btn-default search">
<i class = "glyphicon glyphicon-search"></i>
</button>
</span>
<span class="input-group-btn">
<button class = "btn btn-default random">
<i class = "glyphicon glyphicon-random"></i>
</button>
</span>
</div>
</form>
<div class= "row result-group">
<div class = "col-xs-12 col-sm-8 col-sm-offest-2 col-md-6 col-md-offset-3">
<div class = "results" id = "resultsID">
</div>
There are two issues. 有两个问题。
First, your button is implicitly submitting the form (its default type is submit
). 首先,您的按钮隐式提交表单 (其默认类型为submit
)。
So you need to add type="button"
to your button
elements. 因此,您需要在button
元素中添加type="button"
。
Secondly, the returned html cannot be sent to the jQuery constructor because it is not syntactically correct according to the jQuery constructor. 其次,返回的html无法发送到jQuery构造函数,因为根据jQuery构造函数,语法上不正确。 There is a logged error message: " Uncaught Error: Syntax error, unrecognized expression ". 没有记录的错误消息:“ 未捕获的错误:语法错误,无法识别的表达式 ”。 The result should be sent to the .html()
function. 结果应发送到.html()
函数。
$("<div>").html(wikiJSON.query.search[0].snippet).appendTo("#resultsID")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.