开发者

sending parameters to a jquery function

I have the following function which works very well within a $(document).ready(function(){

$('.threadWrapper > .littleme').click(function() {
        $(this).next().toggle();
        $(this).toggle();
        $('.littlem开发者_开发知识库e').not(this).next().hide();
        $('.littleme').not(this).show();

        // re-run masonry
        $('#mainContent').masonry();

        return false;
    }).next().hide();

What I want to be able to do is call this from inline javascript Each div element that contains the threadWrapper class also has its own id. What I want to do is to be able to trigger this function using inline javascript calls and sending an id as a parameter. For example:

$(function(id){
$('#id > .littleme').next().toggle();
$('#id > .littleme').toggle();
etc. etc.
});


Just concatenate the strings for the selector like this:

function toggleStuff(id) {
  $('#' + id + ' > .littleme').next().toggle();
  $('#' + id + ' > .littleme').toggle();
  //etc. etc.
}

Define this outside your document.ready function so it's available. Also, you can shorten this if you want as well down to:

  $('#' + id + ' > .littleme').toggle().next().toggle();


You can just use a regular javascript function:

function Something(id) // id is a jquery object
{
  id.find('.littleme').next().toggle();
  id.find('.littleme').toggle();
  etc. etc.
}


There is no need to call any inline javascript from your elements. What I would recommend is the following:

$('.threadWrapper').click(function() {
    $(this).find(".littleme").next().toggle();
    $(this).find(".littleme").toggle();
    etc. etc.
});

Looking at your selectors, .littleme is a direct descendant of .threadWrapper. So if you bind a click event to all .threadWrappers you can select the .littlemes by searching within the current context.

Also, if you're interested, those two statements can be consolidated using .end:

$(this).find(".littleme").next().toggle().end().toggle();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜