开发者

jquery show/hide two divs on click and hide link

Im using the following JS

<a href=# onClick="if($(this).next('div').css('display') == 'none') { $(this).next('div').show('fast'); } else { $(this).next('div').hide('fast'); } return false;">Add a Street Address</a>

and the following html

<div id=entry>
  <div id=label>Street</div>
  &l开发者_如何学Got;div id=input><input name="" type="text" class="longtext" /></div></div>
<div id=entry>
  <div id=label>City/Town</div>
  <div id=input><input name="" type="text" class="longtext" /></div></div>

How would i modify the JS to show/hide both of those divs at once, and then make the link disappear?


a. you better off using class instead of id where both share the same value (e.g. entry)

<div class=entry>
  <div id=label>Street</div>
  <div id=input><input name="" type="text" class="longtext" /></div></div>
<div class=entry>
  <div id=label>City/Town</div>
  <div id=input><input name="" type="text" class="longtext" /></div></div>

b. Hiding both divs can be done as:

$('.entry').hide();

hiding the clicked link

$(this).hide();
return true;

e.g.

<a id='myLinkId' href='#'>Click To Hide</a>

$('a#myLinkId').click(function(){
    $('.entry').hide();
    $(this).hide();
    return true;
});


First give an id to your link tag like 'link', then give you two dives two different ids, then write a js function like this :

show_hide = function()
{
    if(document.getElementById('link').style.display == 'none'){
         document.getElementById('link').style.display = 'inline';
         document.getElementById('entry1').style.display = 'inline';
         document.getElementById('entry2').style.display = 'inline';
    }else{
         document.getElementById('link').style.display = 'none';
         document.getElementById('entry1').style.display = 'none';                  
         document.getElementById('entry2').style.display = 'none';
    }
}


IDs need to be unique so I have changed the ids to classes. Also, I have changed the code from being inline to being unobtrusive The jQuery would be something like the following

$(function() {
    $('#addressLink').click(function() {
        $('div.entry').toggle();
        $(this).hide();
        return false; // prevent the default anchor behaviour
    });    
});


<a id="addressLink" href="#">Add a Street Address</a>
<div class="entry">
  <div class="label">Street</div>
  <div class="input"><input name="" type="text" class="longtext" /></div>
</div>
<div class="entry">
  <div class="label">City/Town</div>
  <div class="input"><input name="" type="text" class="longtext" /></div>
</div>

Assuming that you want the <div> elements to be hidden initially, simply add $('div.entry').hide(); into the document ready handler. There are other techniques that you can use here, but I would suggest hiding using JavaScript for graceful degradation purposes

Here's a Working Demo. Add /edit to the URL to see the code

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜