开发者

Get DIV index value

开发者 https://www.devze.com 2022-12-18 04:55 出处:网络
I am stuck with a problem here, please help. What my requirement is to get the index value of the div clicked. Have 2 lists, and i need to call a function doSomething(); only when the user clicks the

I am stuck with a problem here, please help. What my requirement is to get the index value of the div clicked. Have 2 lists, and i need to call a function doSomething(); only when the user clicks the first div set. Is there anyway that i can achieve it.

The scripts and HTML is as follows

$(document).ready(function() {
 $(".list-wrapper li").click(function() {
    var index = $(".list-wrapper div").index(this);
    alert(index);
    });
});

<div class="list-wrapper">
<ul>
<li>List 1</li>
<li>List 2</li>
<li>List 3</li>
</ul>
</div>

<div class="list-wrapper">
<ul>
<li>List 1</li>
<li>List 2&l开发者_运维问答t;/li>
<li>List 3</li>
</ul>
</div>

Please help...


jQuery has powerful selectors, so usually you don't need to check the index after the event. For example:

For the first div on your page:

$(".list-wrapper:first").click(doSomething);

For the first <li>s in every list:

$(".list-wrapper li:first-child").click(doSomething);

If you still want to find the index, you need to search for the parent div of the clicked li. Also, the selector .list-wrapper div is empty - you don't have any divs in list-wrapper. This will work:

var parent = $(this).closest('div')
var index = $(".list-wrapper").index(parent);


if it only needs to be on the first one use the :first selector

http://api.jquery.com/first-selector/

$("div.list-wrapper:first").find("li").click(function() {...


There are many ways to do this:

$('div.list-wrapper').first().click(function() { doSomething(); });

and

$("div.list-wrapper:first").click(function() { doSomething(); });

and

$('div.list-wrapper').eq(0).click(function() { doSomething(); });

are the first ones that come to mind. Pro-tip, include the element type before the class for speed (div.blah faster than .blah)

Or to just get the index:

var index = $('div.list-wrapper').index(this);

replace 'this' with the parent for specificity


Try This :

<ul><li id="foo">foo</li><li id="bar">bar</li><li id="baz">baz</li></ul>


var listItem = document.getElementById('bar');
alert('Index: ' + $('li').index(listItem));

See this for more info : http://api.jquery.com/index/

0

精彩评论

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