开发者

jQuery - Display occurrence number of divs

开发者 https://www.devze.com 2023-04-13 09:37 出处:网络
I have the following html... <div class=\"display\">sometext</div> <div class=\"display\">sometext</div>

I have the following html...

<div class="display">sometext</div>
<div class="display">sometext</div>
<div class="display">sometext</div>

Using jQuery I want to be able to click the first div and an alert is displayed saying that you have clicked the first d开发者_高级运维iv and so on. I know how to count the number of divs with a specific class but not how to tell which one is clicked.


Behind the scenes, .index() also loops through all previous elements. The following alternative is more efficient than .index() when the element has lots of siblings.

$(".display").each(function(i){
    $(this).click(function(){
        alert("Clicked div.display, number " + i);
    }
});


I'm not sure about 'first' as such, but you could try:

$('.display').click(
    function(){
        alert("You clicked div number: " + ($(this).index('.display') + 1) + ", of " + $('.display').length);
    });

JS Fiddle.

References:

  • .index().


Here's a simple way.

$divs = $('.display'); 
$divs.click(function(){
     alert( $divs.index($(this)) ); 
})

Fiddle to go with it.


The answer is simple and proven by this jsfiddle:

var containers = jQuery('.display');
containers.bind('click', function(event){
    alert('Clicked element no. ' + (containers.index(this)+1));
});

Please let me know if it helped.


You can do just:

HTML

<div class="display" name="1">sometext</div>
<div class="display" name="2">sometext</div>
<div class="display" name="3">sometext</div>

JavaScript

$('.display').click(function(){
    alert($(this).attr('name'));
});

Demo : http://jsfiddle.net/SzwJU/


Why use jQuery? You can write a simple javascript that is triggered onclick by the div.

0

精彩评论

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