我的目标是创建一个实时搜索功能,寻找标题,导演和打开爬行,然后在标题上的可点击事件显示信息,并在人物上的可点击事件。 我遇到的问题是如何创建事件,以及如何获取角色的名称,而不仅仅是链接。 当我遍历字符时,我只得到链接。
<!-- The html for the live search -->
<form action="" id="searchArea">
<!-- The input for searching -->
<input type="search" id="search">
</form>
//the data from jquery will present here
<div id="update">
</div>
<!-- closing -->
//Jquery Document
$(function(){
// create a keyup
$('#search').keyup(function (e) {
e.preventDefault();
//getting the search value from input
var searchTerm = $('#search').val();
//insensitive case
var exp = new RegExp(searchTerm, 'i');
//getting the swapi film data
$.getJSON("https://swapi.dev/api/films/", function (data) {//
//creating a output future values of data
var output = '<ul>'
//iterate through data.results with $.each
$.each(data.results, function (key, value) {
//if statment for searching the title, director, opening crawal
if((value.title.search(exp)!= -1) || (value.director.search(exp)!= -1) || (value.opening_crawl.search(exp)!= -1)){
//create a list
//output with, title, director, opening crawl and characters
output += '<li>';
output+='<h4>'+value.title+'</h4>' //need a clickable event for to get the charachters data and not just the links
output+='<li>'+value.director+'</li>'
output+='<p>'+value.opening_crawl+'</p>'
output+='</li>';
}
});
//closing the ul
output += '</ul>'
$('#update').html(output);
//output to html
}//json
);//key up
});
});//doc.ready
为了能够识别您点击的标题,您首先需要向标题添加一个标识符。 我确信在从API接收到的数据中,您得到的每个标题都有一个唯一的id。 让我们假设它被称为titleid。 所以现在您将id添加到标题中
output+='<h4 id="'+value.titleId+'">'+value.title+'</h4>';
在将输出添加到DOM之后,可以向所有标题添加一个click事件
$('#update').html(output);
$('h4').on('click', function()
{
console.log($(this).attr('id')); // here we get our titleId
// here we have to do our next action
}
要获得标题的详细信息,您需要另一个API调用。 我猜一定有一个调用通过一个标题的唯一ID从其获取详细信息。 这个你应该先弄清楚。 然后执行此API调用,并以获取和显示标题列表相同的方式显示标题详细信息。