简体   繁体   中英

Altering the CSS of a span with a div by class inside $(this)

I have the following HTML structure:

<div class=module onclick="systemMenuRevealModule(this)"><span>Dashboard</span> 
    <div class=module_function><span>Performance</span></div>
    <div class=module_function><span>Alerts</span></div>
</div>
<div class=module onclick="systemMenuRevealModule(this)"><span>Favorites</span>
    <div class=module_function><span>Dashboard</span></div>
</div>

Script:

<script>
    function systemMenuRevealModule(el){
        $('.module_function span').css('display', 'none');
        $(this).find(".module_function span").css('display', 'block');


    }
</script>

I am trying to reveal only the span's that are within the div being clicked. This is part of a menu structure code. I am trying to make this work without IDs, to make the code more universal. I don't see any errors in console, and nothing happens?

That's because this in the click handler refers to the window object not the clicked element. You are passing the clicked element to the handler, use it:

function systemMenuRevealModule(el) {
    $('.module_function span').css('display', 'none');
    $(el).find(".module_function span").css('display', 'block');
}

An alternative without using onclick attribute:

var $spans = $('.module_function span');
$('.module').on('click', function() {
     // `this` here refers to the clicked element
     $spans.hide();
     $(this).find(".module_function span").show();
});

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