【发布时间】:2021-12-04 03:21:01
【问题描述】:
我正在使用 jquery 从电影 API 调用数据,它有一个端点,我可以在其中调用带有 id 的特定节目。主页显示电影,单击它们应该调用 API 的另一个端点。以下是我的代码:
$(function (){
let $movies = $('#showList')
$.ajax({
method:'GET',
url:'http://api.tvmaze.com/shows',
success: function(movies){
$('#show').hide()
$('#showList').removeAttr('hidden');
$.each(movies, function(i,movie){
$movies.append('<li class="list"><a id="ss" href="'+ movie._links.self.href+'">'+ movie.name +'</a></li>')
})
}
})
})
$('body').on('click','.list a',function(event){
event.preventDefault();
$('#showList').hide();
$('#show').empty()
let currentId = event.target.id;
console.log(currentId)
$.ajax({
method:'GET',
url:'http://api.tvmaze.com/shows/'+currentId,
success: function(movies){
$('#show').append('<h1>'+ movies.name +'</h1>')
}
})
$('#show').show();
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TV Shows</title>
</head>
<body>
<h1>TV Shows</h1>
<div id="show" hidden></div>
<ul id="showList" hidden></ul>
<form id="searchForm">
<input type="text" id="search_term">
<label for="text">Search</label>
<button>Submit</button>
</form>
<a id="homelink" href="/" hidden>Back to All Shows</a>
<footer>Swayam Shah, 10471353</footer>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script src="/public/js/index.js"></script>
</body>
</html>
当我点击电影链接时如何获取此 ID? console.log 显示为空。
【问题讨论】:
-
你试过
$(event.target).attr('id') -
返回未定义,不知道为什么
-
登录
event.target看看你得到了什么。这可以在事件冒泡期间改变。你可能想要event.currentTarget -
我尝试了 event.currentTarget,我认为我的代码的其他部分是错误的
-
当我 console.log event.target 我得到:Homeland
标签: javascript html jquery