如何在没有占位符的情况下在HTML中呈现JSON的结果DIVS

时间:2017-05-31 12:21:56

标签: javascript jquery html json

用户故事:用户可以搜索维基百科。结果仅限于5篇文章,用户可以看到文章的标题+介绍。

开发故事:查询是通过HTML输入字段提供的。维基百科API是通过getJSON请求的,并且给出的数据被组织并在for循环中给出占位符div。

问题:如何删除HTML中的重复性?我想删除占位符div。 更具体一点:我不想为每个结果提供5x div,而是希望有一个动态。

代码正常,见下文。工作示例 - Github页面HERE

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

	<!-- Custom CSS -->
	<style>
    @import url('https://fonts.googleapis.com/css?family=Droid+Sans');
 
    /*
    #300032
    #06000a
    #c43235
    #e6e6e8
    */
	
	html, body{
	height: 100%;
	}
	
	.bg {
	  display: flex;
	  justify-content: center;
	  align-items: center;
      background-color: #FFF;
    }
	.search {
      padding: 10%;
      max-width: 50%;
    }
	
	#results{
	     padding: 10%;
	}
	
	.bg, .search, #results {
	  flex: 1 100%;
	  min-height: 100%;
	}
	
	/* Medium screens */
	@media all and (max-width: 800px) {
	.bg {display: flex; flex-direction: column;}
	}
	
    span, h1{
      font-size: 2em;
      font-family: 'Droid Sans', sans-serif;
      font-weight: 600;
      color: #000;
      padding-right: 20px;
    }
    .random{
	font-family: 'Droid Sans', sans-serif;	
	font-size: 1em;
      font-weight: 400;
      color: #000;
    }
    .title {
	font-family: 'Droid Sans', sans-serif;
	font-size: 1em;
	font-weight: bolder;
    }
	
	.wikiArticle {
	  font-family: 'Droid Sans', sans-serif:
      color: #FFF;
	  margin: auto;
	}
    .wikiArticle:hover {
      background-color: #c43235;
      color: #FFF;
    }
	
	.wikiArticle a{
		color: #e6e6e8;
		text-decoration: none;
	}
	
	.hidden {
		display: none;
	}
	
	input{
		padding: .5rem;
		border-radius: .25rem;
		vertical-align: middle;
		border: 1px solid rgba(0, 0, 0, 0.2);
		margin-top: 1rem;
		margin-bottom: 1rem;
		box-sizing: border-box;
    		width: 100%;
	}
	
	#searchButton {
		color: #ccc;
		background-image: none;
		background-color: transparent;
		border-color: #ccc;
	}
	
	#searchButton:hover{
		color: #fff;
		background-color: #c43235;
		border-color: #c43235;
	}
	
	input:focus,
	select:focus,
	textarea:focus,
	button:focus {
		outline-color: #c43235;
	}
	
	.search img{
		vertical-align: baseline;
    		width: 30%;
	}
		
	.search a{
		text-decoration: none;
	}
		
	</style>
  </head>
  <body>
		<div class="bg">
			<div class="search">
				<a href="https://www.mariokandut.com" target="_blank">
					<img src="https://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/1122px-Wikipedia-logo-v2.svg.png">
				</a>
				<span>Instant Search</span><br />
				<input type="text" placeholder="Type your query" name="searchTermInput" id="searchTermInput" onkeypress="handleKeyPress(event)">
				<button onclick="wikiSearch();" type="button" id="searchButton" class="btn">Go</button>
				<br />
				<span class="random">
					<a href="https://en.wikipedia.org/wiki/Special:Random" target="_blank">Random Magic</a>
				</span>
				
			</div>		
			<div id="results" class="hidden">
			<h1>Instant Results</h1>
				<div id="wikiOut0" class="wikiArticle">
					<a id="wikiLink0" href="" target="_blank">
						<p class="title" id="titleOut0"></p>
						<p id="snippetOut0"></p>
					</a>
				</div>
				<div id="wikiOut1" class="wikiArticle">
					<a id="wikiLink1" href="" target="_blank">
						<p class="title" id="titleOut1"></p>
						<p id="snippetOut1"></p>
					</a>
				</div>
				<div id="wikiOut2" class="wikiArticle">
					<a id="wikiLink2" href="" target="_blank">
						<p class="title" id="titleOut2"></p>
						<p id="snippetOut2"></p>
					</a>
				</div>
				<div id="wikiOut3" class="wikiArticle">
					<a id="wikiLink3" href="" target="_blank">
						<p class="title" id="titleOut3"></p>
						<p id="snippetOut3"></p>
					</a>
				</div>
				<div id="wikiOut4" class="wikiArticle">
					<a id="wikiLink4" href="" target="_blank">
						<p class="title" id="titleOut4"></p>
						<p id="snippetOut4"></p>
					</a>
				</div>
			</div>
		</div>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <script>
	
	//function to make ENTER button a click
	function handleKeyPress(e){
	var key=e.keyCode || e.which; 
	if (key==13){ //check if button is enter button
		wikiSearch();
		};
	}
	
    function wikiSearch() {
	  //Search via Generator API Method
      var searchTerm = document.getElementById("searchTermInput").value;
	  //console.log(searchTerm);
	  //Querylimit API (gsrlimit=5) limit outcome to 5 queries
	  var queryLimit = 5;
	  var wikiURL = "https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrnamespace=0&gsrlimit=" + queryLimit + "&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=" + searchTerm + "&format=json&callback&callback=?";
	  console.log(wikiURL);
	  $.getJSON(wikiURL, function(data){
		//Get PageID with Object.keys
		var pageID = Object.keys(data.query.pages);
		console.log(pageID);
		data.query.pages[pageID[0]].extract;
		for(var i=0; i < queryLimit; i++){
				document.getElementById("titleOut"+i).innerHTML = data.query.pages[pageID[i]].title;
				document.getElementById("snippetOut"+i).innerHTML = data.query.pages[pageID[i]].extract.substring(0,150) + "...";
				var objectLink = document.getElementById("wikiLink"+i);
				objectLink.setAttribute("href", "https://en.wikipedia.org/?curid=" + pageID[i]);
				console.log(objectLink);
		};
		//Other option: Open Search https://www.mediawiki.org/wiki/API:Opensearch
		//var wikiURL = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchTerm + "&limit=5&namespace=0&format=json&callback=?"
		//Different Option, but no URL output possible. "list=search";
		//https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&continue=&srsearch=" + searchTerm + "&srwhat=text&srprop=size|wordcount|timestamp|snippet|titlesnippet&utf8=1&callback=?";
		$("#results").removeClass("hidden");
      });
    }
    </script>
  </body>
</html>

2 个答案:

答案 0 :(得分:0)

[已更新] 您需要删除所有占位符,并且需要在脚本中将其设置为动态,您可以在document.getElementById(...作业之前放置以下块,

var wikiDiv= document.createElement('DIV');
    document.body.appendChild(wikiDiv);
    wikiDiv.innerHTML = '<div id="wikiOut'+i+'" class="wikiArticle"><a id="wikiLink'+i+'" href="" target="_blank"><p class="title" id="titleOut'+i+'"></p><p id="snippetOut'+i+'"></p></a></div>';

以下是有效的演示: https://jsfiddle.net/fev60Lwn/1/

希望这有帮助!

答案 1 :(得分:0)

您可以将一个div作为模板

        <div id="results" class="hidden">
        <h1>Instant Results</h1>
            <div id="wikiOut" class="wikiArticle" style="display:none">
                <a id="wikiLink" href="" target="_blank">
                    <p class="title" id="titleOut"></p>
                    <p id="snippetOut"></p>
                </a>
            </div>
        </div>

然后为每篇文章克隆它

    $('.wikiArticle:not(#wikiOut)').remove();
    for(var i=0; i < queryLimit; i++){
            var tmpl = $('#wikiOut').clone();
            tmpl.find("#titleOut").attr('id',"titleOut"+i).html(data.query.pages[pageID[i]].title);
            tmpl.find("#snippetOut").attr('id',"snippetOut"+i).html(data.query.pages[pageID[i]].extract.substring(0,150) + "...");
            $("#wikiLink").attr({'id':"snippetOut"+i,"href": "https://en.wikipedia.org/?curid=" + pageID[i]});
            tmpl.appendTo('#results').show();
            console.log(objectLink);
    };