简体   繁体   中英

jquery mutually exclusive click

I have 3 divs with 2 possible image tags for each (active or inactive). If one div is clicked to be active the other divs must be set to inactive. How do I accomplish this with img tags and what happens if user has javascript disable?

Do you mean something like this?

<div class="block" id="block1">
    <img src='inactive_block1.jpg'>
</div>

<div class="block" id="block2">
    <img src='inactive_block2.jpg'>
</div>

<div class="block" id="block3">
    <img src='inactive_block3.jpg'>
</div>

Using a library like jQuery , the javascript would look like:

$(function() {
    $('.block').click(function() {
       $('#block1').find('img').attr('src', 'inactive_block1.jpg');
       $('#block2').find('img').attr('src', 'inactive_block2.jpg');
       $('#block3').find('img').attr('src', 'inactive_block3.jpg');
       $(this).find('img').attr('src', 'active_' + $(this).attr('id') + '.jpg');
    });
});

With the above, if you have inactive_block1.jpg , inactive_block2.jpg , inactive_block3.jpg and active_block1.jpg , active_block2.jpg and active_block3.jpg you should get what you want.

It's up to you whether its worth it or not to have javascript disabled fallbacks, mostly depending on whether you expect a large amount of your audience to have javascript disabled.

if a user has JavaScript disabled, there is nothing you can do that is JavaScript-based to deal with dynamically modifying the page. The only other option you have is to create a "deprecated" version of your functionality that requires a page request after each click.

I would recommend researching how to dynamically add/remove classes from elements in the DOM, that is how I would approach this problem. You could easily do a jQuery select for all elements who are "active" on click and set a "disabled" class on them, that way you are essentially blacking out everything except the element you've clicked.

Does that make sense?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM