开发者

How to Reduce Size of This jQuery Script and Make it More Flexible?

I just created script that shows/hides (toggles) block of HTML. There are four buttons that each can toggle its HTML block. When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button... it hides that HTML block and shows new one.

Here is what I have at the moment:

$('.btn_add_event').click( function() {

    $('.block_link, .block_photos, .block_videos').hide();
    $('.block_event').toggle();

});

$('.btn_add_link').click( function() {

    $('.block_event, .block_photos, .block_videos').hide();
    $('.block_link').toggle();

});

$('.btn_add_photos').click( function() {

    $('.block_event, .block_link, .block_videos').hide();
    $('.block_photos').toggle();

});

$('.btn_add_videos').click( function() {

    $('.block_event, .block_link, .block_photos').hide();
    $('.block_videos').toggle();

});

Any ideas how to reduce code size? Also开发者_运维知识库, this script isn't very flexible. Imagine to add two new buttons and blocks.


like Sam said, I would use a class that all the blocks share, so you never have to alter that code. Secondly, you can try 'traversing' to the closest block, therefore avoiding it's name. That approach is better than hard coding each specific block, but if the html dom tree changes you will need to refactor. Last, but best, you can pass in the class name desired block as a variable to the function. Below is something you can copy paste that is close to what you started with.

$('.myAddButtonClass').click( function() {

    $('.mySharedBlockClass').filter(':visible').hide();
//find a good way to 'traverse' to your desired block, or name it specifically for now.
//$(this).closest(".mySharedBlockClass").show()  complete guess
    $('.specificBlockClass').show();
});


I kept reading this "When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button" thinking that my eyes were failing me when Its just bad English.

If you want to make it more dynamic, what you can do is add a common class keyword. Then when the click event is raise. You can have it loop though all the classes that have the keyword and have it hide them all (except the current one that was clicked) and then show the current one by using the 'this' keyword.


you can refer below link,

http://chandreshmaheshwari.wordpress.com/2011/05/24/show-hide-div-content-using-jquery/

call function showSlidingDiv() onclick event and pass your button class dynamically.

This may be useful.

Thanks.


try this

   $('input[type=button]').click( function() {
        $('div[class^=block]').hide(); // I resumed html block is div
        $(this).toggle();
});


Unfortunatly I couldn't test it, but if I can remember right following should work:

function toogleFunc(clickObject, toogleTarget, hideTarget)
{
  $(clickObject).click(function()
  {
    $(hideTarget).hide();
    $(toogleTarget).toggle();
  });
}

And the call:

toogleFunc(
  ".btn_add_videos",
  ".block_videos", 
  ".block_event, .block_link, .block_photos"
);

and so far


Assuming the buttons will only have one class each, something like this ought to work.

var classNames = [ 'btn_add_event', 'block_link', 'block_photos', 'block_videos' ];

var all = '.' + classNames.join(', .'); // generate a jquery format string for selection

$(all).click( function() {

    var j = classNames.length;

    while(j--){
     if( this.className === classNames[j] ){

        var others = classNames.splice(j, 1); // should leave all classes but the one on this button

        $('.' + others.join(', .')).hide();
        $('.' + classNames[j]).toggle();

     }
    }
}

All the buttons have the same handler. When the handler fires, it checks the sender for one of the classes in the list. If a class is found, it generates a jquery selection string from the remaining classes and hides them, and toggles the one found. You may have to do some checking to make sure the strings are generating correctly.


It depends by how your HTML is structured.

Supposing you've something like this

<div class="area">
  <div class="one"></div>
  <div class="two"></div>
  <div class="three"></div>
</div>
...
<div class="sender">
  <a class="one"></a>
  <a class="two"></a>
  <a class="three"></a>
</div>

You have a class shared by the sender and the target.

Your js would be like this:

$('.sender > a').click(function() {
  var target = $(this).attr('class');
  $('.area > .' + target).show().siblings().hide();
});

You show your real target and hide its siblings, which aren't needed.


If you put the class postfixes in an array, you can easily make this code more dynamic. This code assumed that it doesn't matter in which order toggle or hide are called. If it does matter, you can just remember the right classname inside the (inner) loop, and toggle that class after the loop.

The advantage to this approach is that you can extend the array with an exta class without needing to modifying the rest of the code.

var classes = new Array('videos', 'event', 'link', 'photos');

for (var i = 0; i < classes.length; ++i)
{ 
    $('.btn_add_' + classes[i]).click( 
    function() 
    {
        for (var j = 0; j < classes.length; ++j)
        {
            if (this.hasClass('btn_add_' + classes[j]))
            {
                $('.block_' + classes[j]).toggle();
            }
            else
            {
                $('.block_' + classes[j]).hide();
            }
        }

    });
}

You could make this code more elegant by not assigning those elements classes like btn_add_event, but give them two classes: btn_add and event, or even resort to giving them id's. My solution is based on your description of your current html.


Here is what I think is a nice flexible and performant function. It assumes you can contain your links and html blocks in a parent, but otherwise it uses closures to precalculate the elements involved, so a click is super-fast.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" ></script>

<script type="text/javascript">

  // Enables show/hide functionality on click. 
  // The elements within 'container' matching the selector 'blocks' are hidden
  // When elements within 'container' matching the selector 'clicker' are clicked
  //  their attribute with the name 'clickerAttr' is appended to the selector 
  //  'subject' to identify a target, usually one of the 'blocks'. All blocks 
  //  except the target are hidden. The target is shown.
  // 
  // Change clickerAttr from 'linkTarget' to 'id' if you want XHTML compliance
  // 
  // container: grouping of related elements for which to enable this functionality
  // clicker: selector to element type that when clicked triggers the show/hide functionality
  // clickerAttr: name of the DOM attribute that will be used to adapt the 'subject' selector
  // blocks: selector to the html blocks that will be shown or hidden when the clicker is clicked
  // subject: root of the selector to be used to identify the one html block to be shown
  // 
  function initToggle(container,clicker,clickerAttr,blocks,subject) {

    $(container).each(
        function(idx,instance) { 
            var containerElement = $(instance);
            var containedBlocks = containerElement.find(blocks);    

            containerElement.find(clicker).each(function(idxC, instanceClicker) {

                var tgtE = containerElement.find(subject+instanceClicker.getAttribute(clickerAttr));
                var clickerBlocks = containedBlocks.not(tgtE);

                $(instanceClicker).click(function(event) { 
                    clickerBlocks.hide();
                    tgtE.toggle();
                });
            });

            // initially cleared
            containedBlocks.hide(); 
        }
    );
  }

  $(function() {

    initToggle('.toggle','a.link','linkTarget','div.block','div.');

  });
</script>

</head>
<body>

Example HTML block toggle:

<div class="toggle">
    <a href="javascript:;" linkTarget="A" class="link"> a </a> <br />
    <a href="javascript:;" linkTarget="B" class="link"> b </a> <br />
    <a href="javascript:;" linkTarget="C" class="link"> c </a> <br />
    <div class="A block">   A       </div>
    <div class="B block">   B       </div>
    <div class="C block">   C       </div>
</div> <!-- toggle -->

This next one is not enabled, to show scoping.

<div class="toggle2">
    <a href="javascript:;" linkTarget="A" class="link"> a </a> <br />
    <div class="A block">A</div>
</div> <!-- toggle2 -->

This next one is enabled, to show use in multiple positions on a page, such as in a portlet library.    

<div class="toggle">
    <a href="javascript:;" linkTarget="A" class="link"> a </a> <br />
    <div class="A block">A</div>
</div> <!-- toggle (2) -->

</body>
</html>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜