Get value of List Item with jQuery

限于喜欢 提交于 2020-01-12 04:44:08

问题


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

<ul id='uItem'>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>

回答1:


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);
});



回答2:


$('#uItem li').click(function(){
 var $this = $(this);
 alert('Text ' + $this.text() + 'Index ' + $this.index());
})

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




回答3:


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);
})



回答4:


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




回答5:


$('ul li').click(function(){ 
     var value = $(this).text();
     var index = $('li').index($(this));
});

check this for more details



来源:https://stackoverflow.com/questions/5548827/get-value-of-list-item-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!