【问题标题】:How do I get the id present in the link using jQuery?如何使用 jQuery 获取链接中的 id?
【发布时间】: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


【解决方案1】:

您没有在锚标记中提及 id 属性。

     $movies.append('<li class="list"><a href="'+ movie._links.self.href+'">'+ movie.name +'</a></li>')

【讨论】:

  • 我加了,还是不行
  • @swombhai,你能在讨论中添加带有 id 属性的锚点吗?
【解决方案2】:

只能用 currentID 替换 URL

【讨论】:

    【解决方案3】:

    使用“this”对我有用。

    $("a").click(function() {
        console.log($(this).attr("id"));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 2011-07-27
      • 1970-01-01
      相关资源
      最近更新 更多