How to get ID of clicked element with jQuery

后端 未结 5 1930
花落未央
花落未央 2020-12-08 18:38

I have the following html:

link
link

        
相关标签:
5条回答
  • 2020-12-08 19:16

    Your id will be passed through as #1, #2 etc. However, # is not valid as an ID (CSS selectors prefix IDs with #).

    0 讨论(0)
  • 2020-12-08 19:16

    @Adam Just add a function using onClick="getId()"

    function getId(){console.log(this.event.target.id)}
    
    0 讨论(0)
  • 2020-12-08 19:19

    Your IDs are #1, and cycle just wants a number passed to it. You need to remove the # before calling cycle.

    $('a.pagerlink').click(function() { 
        var id = $(this).attr('id');
        $container.cycle(id.replace('#', '')); 
        return false; 
    });
    

    Also, IDs shouldn't contain the # character, it's invalid (numeric IDs are also invalid). I suggest changing the ID to something like pager_1.

    <a href="#" id="pager_1" class="pagerlink" >link</a>
    
    $('a.pagerlink').click(function() { 
        var id = $(this).attr('id');
        $container.cycle(id.replace('pager_', '')); 
        return false; 
    });
    
    0 讨论(0)
  • 2020-12-08 19:19

    First off you can't have just a number for your id unless you are using the HTML5 DOCTYPE. Secondly, you need to either remove the # in each id or replace it with this:

    $container.cycle(id.replace('#','')); 
    
    0 讨论(0)
  • 2020-12-08 19:24

    You just need to remove the hash from the beginning:

    $('a.pagerlink').click(function() { 
        var id = $(this).attr('id').substring(1);
        $container.cycle(id); 
        return false; 
    }); 
    
    0 讨论(0)
提交回复
热议问题