开发者

Manipulating one of many?

I have some markup, like so...

<div id="items">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

I want to write some functions to affect each one using jQuery开发者_StackOverflow中文版. Something like...

$(".item").click(function(i){
    i.hide();
});

Can someone give me a brief explanation how to make this work? Should I use .each()?


you can do this :)

$(".item").live('click',function(){
    $(this).hide();
});


(a) The documentation is clear on what the event handlers do.

(b) Like most jquery methods (and the exceptions all state specifically that they are exceptions), .click will be applied to each member of the set selected by the jquery object. So, no, you don't need to use .each if you want each of them to have the same function installed as the event handler.

(c) this or event.currentTarget (or in your example, i.currentTarget) is the way to access the dom node which is the recipient of the event. i in your example will be the event object.


it works too without the each

$(".item").click(function() {
   $(this).hide();
});


$('.item').each(function(index){
    $(this).bind('click', function(){
        $(this).hide();
        //alert("hiding item nr: "+index);
    });
});


Yes, you can use each, like this:

$(".item").each(function(){
   //Here, use $(this) to reference current element 
   $(this).hide();
});

.each() applies the function you pass to every element in the matched selector, referencing with this the current element.

It has optional parameters and other things. Here you can learn more: http://api.jquery.com/jQuery.each/

Hope this helps. Cheers


This hopefully does what you want. Let us know if that works, hope that helps.

$(".item").each(function(){
     $(this).click(function () {
         $(this).hide();
     });
});


You want to use $(this) instead of i inside the handler function. The argument to the handler is an event object, which contains information about the event (such as the mouse coordinates where it was clicked, and other stuff). Probably somewhere in i is the object that was clicked, but you can access "whichever object was clicked" much more easily using this.

You don't have to use each because jQuery automatically binds the handler to each of the elements matched by the query ".item".

$(".item").click(function(i){
    $(this).hide();
});

Edit: Added $(...) around this, as instructed in the documentation. (For some reason, it worked for me without the $, but apparently you need it.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜