开发者

How do I optimize this bit of jquery?

I'm looking for a way to shorten this bit of code I've put together.

I have several basic UI elements that, when clicked, slide down to reveal more information.

As I have it written now, each element has it's own p id and a id.

Is there a way to pass the id clicked to the function being run so I don't have to hand code 10+ elements?

        $(document).ready(function() {
        //hides info paragraph as soon as the DOM is ready (before the page loads)
        $('div.info > p').hide();

        开发者_开发技巧// Toggles the slickbox on click
        $('#infoToggle').click(function() {
            $('#info').slideToggle(400);
            return false;
        });
        $('#moreToggle').click(function() {
            $('#more').slideToggle(400);
            return false;
        });
    });

So instead of "moreToggle" and "infoToggle" I would just have one anon function that ran "XToggle" where X = the id of the link clicked?


Just add all the ids you need to the selector and use this in the click function:

$('#infoToggle, #moreToggle').click(function() {
  $('#' + this.id.replace('Toggle','')).slideToggle(400);
  return false;
});


You could do something like this:

$.each(['info', 'more', 'x'], function(i, value) {
    $('#' + value + 'Toggle').click(function() {
        $('#' + value).slideToggle(400);
        return false;
    });
});

The best, most flexible solution, however, would be to structure your markup in a way that you can make use of DOM relationships to find the relevant elements.


If I understand your question correctly you want a bunch of click handlers that run .slideToggle. If that's true you want something like the following (using multiple selectors to bind to a single click handler):

$('#infoToggle, #moreToggle').click(function() {
    $('#' + $(this).attr('id').replace('Toggle','')).slideToggle(400);
    return false;
});


use $('#'+(this).id+'Toggle').slideToggle(400)


$('.someClass').click(function() {
        $('#' + $(this).attr('id').replace('Toggle','')).slideToggle(400);
        return false;
    });

This would take the id of the clicked item and remove he Toggle part to give the target ID.

Whenever i've done this i've always done it with consistent html, so i'd do something like

<div class='header'>MyTitle</div>
<div class='content'>blah</div>

$('.header').click(function() {
            $(this).next().slideToggle(400);
            return false;
        });


You could put the ids in an array, then iterate through with each, like the following:

$.each(['info', 'more'], function (idx, val) {
    $('#' + val + 'Toggle').click(function () {
        $('#' + val).slideToggle(400);
        return false;
    });
});

A much better solution though, in my opinion might be to use children if your HTML suits.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜