开发者

jQuery - Passing parameters to click, with custom function

开发者 https://www.devze.com 2023-03-24 07:19 出处:网络
So开发者_运维知识库rry, this was a bad question.I couldn\'t work out how to delete it.Actual question and solution here:

So开发者_运维知识库rry, this was a bad question. I couldn't work out how to delete it. Actual question and solution here:

jQuery - Toggle div class on click


There is no need to rebind functions.

Either you bind the click event to a function called toggleSection() which hides the section if it is visible or shows if hidden, or just use this:

$('.section.hidden').click(function() {
    $(this).toggle();
});


jQuery offers an easier way to achieve what you want to do:

.toggleClass()

That way you don't have to implement the changing by hand, but rather work with one click-binding

If of course you would want to just hide and show an object, you could also use

.toggle()

instead of coding it by hand. That is mostly what Javascript-Frameworks do for you, they implement existing functions, that you can tap into, instead of implementing them yourself. Also cross-browser incompatibilities are taken care of (mostly).

If you really want to use jQuery to its fullest potential, please dig through The jQuery API to get to know all the functions it has to offer. That way you will save a lot of time, that you otherwise would put into developing already existing functions.


In this case you can just use

$('.section-legend, .section-collapse').click(hidesection);

and

function hideSection() {
    $(this).addClass('hidden');
}


Just use toggle, if all you need is visibility. If you have custom css for hiding sections, use toggleClass. To illustrate

<script type="text/javascript">
    $(function () {

        $('p').click(function () {
            $('#book').toggle();



            // In javascript, just like many C-derived languages, you can pass 
            // the method's pointer to a variable in. 
            // hidden is the custom class you add and remove from a section
            f = $('#great').is('.hidden') ? funky : hacky;

            f($(this));



            $('#great').toggleClass('hidden');

            $('#amazing').toggleClass('man');

            alert($('#great').attr('class') + ' ---- ' + $('#amazing').attr('class'));
        });


        function funky(section) {
            $(section).html('this is funky!');
        }

        function hacky(section) {
            $(section).html('this is hacky!');
        }

    });
</script>

<div id='book' style='display: none'>Hello</div>

<div id='great' class='diz hidden whatever'>Hai</div>
<div id='amazing' class='spider'>Hai</div>

<p>Stackoverflow rules!</p>

If you want the section to start hidden, put style=display: none to the tag. For your custom hiding/formatting, use toggleClass.

0

精彩评论

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