How to use a value (which is obtained via .text () when clicking lithium) as a selector to hide some div

I have a list of ul li like

<ul class="dropdown-menu" id="dropdown">
   <li><a id='l1' href='javascript:void(0);'>batch1</a></li>
   <li><a id='l2' href='javascript:void(0);'>batch2</a></li>
   <li><a id='l3' href='javascript:void(0);'>batch3</a></li>
   <li><a id='l4' href='javascript:void(0);'>batch4</a></li>
   <li><a id='l5' href='javascript:void(0);'>batch5</a></li>
   <li><a id='l6' href='javascript:void(0);'>batch6</a></li>
</ul>

now, I can get the text value of each li, the problem is that I can not use the text value as selector.What I want to do: I have a div (id - "batch1, batch2 ... batch6"), which I want hide if clicked (except li click). code =

HTML:

<div id="batch1"></div> 
<div id="batch2"></div> ......

JQuery

$(document).ready(function(e) {
    $('body').click(function(event) {

    if($(event.target).is('#l1')) {
       var id = "'#"+$('#l2').text()+"'";
       $(id).hide();
    }
});
});

what should I do. I try for about 24 hours, but still in the dark. and thanks in advance

+5
source share
2 answers

You must add the common class to all the elements #batch1, #batch2so you can immediately configure them.

Then use id as an exception ...

HTML

<div id="batch1" class="batch"></div>
<div id="batch2" class="batch"></div>

Javascript

$('#dropdown').on('click','a', function(e){
    e.preventDefault();
    var id = '#' + $.trim( $(this).text() ); // create the id based on the text

    $('.batch').hide(); // hide all batch elements
    $(id).show(); // show the one that corresponds to the clicked li
});

http://jsfiddle.net/A5Vxm/

+3
$('body').click(function(event) {
    if(event.target.id  == 'l1' ) {
       var id = "#" + $.trim( $('#l2').text() );
       $(id).hide();
    }
});​

DEMO

, DOM ,

    $('body').on('click', 'a', function(event) {
        event.preventDefault();
        if(event.target.id  == 'l1' ) {
           var id = "#" + $.trim( $('#l2').text() );
           $(id).hide();
        }
    });​
+1

All Articles