Get value of List Item with jQuery

后端 未结 5 976
后悔当初
后悔当初 2021-02-08 07:19

How to get value and index of list item onClick event with jQuery?
for example:

  • Item 1
  • Item 2&
相关标签:
5条回答
  • 2021-02-08 07:33

    If you had set a value attribute for your li:

        <ul id='uItem'>
        <li value="item1">Item 1</li>
        <li value="item2">Item 2</li>
        <li value="item3">Item 3</li>
        <li value="item4">Item 4</li>
        </ul>
    

    , then you can retrieve it using jQuery like this:

    $('#uItem li').click(function(){
        var $this = $(this);
        var selKeyVal = $this.attr("value");
        alert('Text ' + $this.text() + 'value ' + selKeyVal);
    })
    
    0 讨论(0)
  • 2021-02-08 07:34
    $('#uItem li').click(function(){
     var $this = $(this);
     alert('Text ' + $this.text() + 'Index ' + $this.index());
    })
    

    Check working example at http://jsfiddle.net/yccyJ/1/

    0 讨论(0)
  • 2021-02-08 07:39
    $('ul li').click(function(){ 
         var value = $(this).text();
         var index = $('li').index($(this));
    });
    

    check this for more details

    0 讨论(0)
  • 2021-02-08 07:40

    Have a look at the index function, http://api.jquery.com/index/

    0 讨论(0)
  • 2021-02-08 07:44

    Combine the use of .index() and .text() (or .html(), if you wish):

    $('#uItem li').click(function() {
        var index = $(this).index();
        var text = $(this).text();
        alert('Index is: ' + index + ' and text is ' + text);
    });
    
    0 讨论(0)
提交回复
热议问题