开发者

which <li> element was clicked?

开发者 https://www.devze.com 2023-04-12 06:11 出处:网络
I have 5 (maybe more) li elements. <ul> <li>One</li> &开发者_运维问答lt;li>Two</li>

I have 5 (maybe more) li elements.

<ul>
 <li>One</li>
 &开发者_运维问答lt;li>Two</li>
 <li>Three</li>
 <li>Four</li>
 <li>Five</li>
</ul>

I want to get which elements was clicked(which row??). If random user clicks Two I want to get $("li:eq(1)")(as typed).

How can I get this result?


You can use jQuery.index. Something like this:

$('ul > li').click(function() {
   alert($(this).index($(this).parent('li'));
});


You can get the text node value of the clicked item with:

$('li').click(function(){
   var clicked = $(this).text();

  alert(clicked+" was clicked");
});


$("#ulId li").click(function() {
   $(this).something(); //the clicked li is $(this), and you can invoke functions on it.
})


If you give your elements an id such as

<ul id="mylist">
 <li id="el_1">One</li>
 <li id="el_2">Two</li>
 <li id="el_3">Three</li>
 <li id="el_4">Four</li>
 <li id="el_5">Five</li>
</ul>

Then you can use $(this).attr(id) in the click handler to determine the id of the clicked element. This will also allow to give non sequential ids to your elements, and will detach what's written in the <li> from the actual value you get. Also, you can encode multiple value in the id (for instance el_5_3) which can be useful sometimes.

$("#mylist li").click(function()
                      {
                      var id = $(this).attr("id").split("_");
                      alert("You clicked the element with id="+id[1]);    
                      });

Working example: http://jsfiddle.net/jFrdp/


Working example: http://jsfiddle.net/tbugV/1/

$("#mylist li").each(function(index)
                     {
                         $(this).data("row", index);
                     }).
                click(function() 
                      {
                        alert($(this).data("row"));   
                      });


 $('html').click(function() {
     var el = e.target;    
     alert(el);
 });


As people just keep posting code, and no explanations, I will try the other way around...

The click event handler is called in the scope of the clicked element, so you can use the this keyword to access the element. You can use $(this) to get a jQuery object that contains the clicked element, so that you can use jQuery methods on it.

Example:

$(document).ready(function(){

  $('ul li').click(function({
    var text = $(this).text();
    alert('You clicked on the item with the text "' + text + '"');
  }));

});


$('li').click(function(){
alert($(this).html());
});

This code will alert one when user will click the one button.

0

精彩评论

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