开发者

how to identify li item using jquery

I've a list

<ul>
  <li><a href="?page=4">one</li>    //no 4
  <li><a href="?page=7">two</li>    //no 7
  <li><a href="?page=14">three</li>  //no 14
  <li><a href="?page=72">four</li>   //no 72
  <li><a href="?page=201">开发者_如何学Cfive</li>   //no 201
</ul>

Now I want to use ajax to load the pages instead of the normal page load. So how do I detect which link the user clicked using jQuery. Say something like

$('id of the element clicked').click(function()({ 
      // Load the page using .ajax() 
});

In the jQuery code above, how do I get id of the element clicked??


You could fetch the id from the href attribute of the clicked anchor using regex:

$('ul a').click(function() {
    var id = this.href.match(/([0-9]+)$/)[1];
    // Load the page using .ajax()  
});

but a better approach IMHO instead of using regex to parse the url is to use HTML5 data-* attributes:

<ul>
  <li><a href="?page=4" data-id="4">one</li>
  <li><a href="?page=7" data-id="7">two</li>
  <li><a href="?page=14" data-id="14">three</li>
  <li><a href="?page=72" data-id="72">four</li>
  <li><a href="?page=201" data-id="201">five</li>
</ul>

and then:

$('ul a').click(function() {
    var id = $(this).data('id');
    // Load the page using .ajax()  
});

Some other answers are suggesting using the id attribute but adding id="4" to the anchor would be invalid markup as according to the specification the id of a DOM element cannot start with a number.


Don't need an id, use $(this) ;)

For example :

$("li").click(function(){
  $(this).//do ajax stuff
});

And if you want to get the href of the clicked element : $(this).children('a').attr('href')


you can get the id attribute of the <a> like this:

$("ul>li>a").click(function(){
   // the id of the anchor
   alert($(this).attr('id'));
   // the id of the li
   alert($(this).parent().attr('id'));
   // link's page id
   alert($(this).attr('href').match(/page=(\d+)$/));
});


to get the id first assign ids to your li and then try this one...

$('li').click(function(){

      $(this).attr('id') ;
});


Bit late but could you not have just done this:

$(function() {
    $('ul li').each(function() {
        $('a', this).click(function(e) {
            e.preventDefault();
            var href = $(this).attr('href');
            $('#somediv').load(href);
        });
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜