简体   繁体   中英

detect click, check attribute value and text inside, and display element

I need to detect click of an element(.menuitem), check the text it contains. And then based on the attribute(is-checked), hide or show other elements. I need this only when clicking that other button.

<div class="items">
  <div class="menuitem" is-checked="true">
    <div class="ytp-menuitem-label">Button 1</div></div>
  <div class="menuitem" is-checked="false">
    <div class="ytp-menuitem-label">Button 2</div></div>
</div>
<div class="element">some content</div>
<div class="element">some more content</div>

$('.menuitem').click(function () {
if ($('.menuitem').text().trim() === "Button 2"){
if ($('[is-checked="true"]'))
  $('.element').css('display', 'block');
if ($('[is-checked="false"]'))
  $('.element').css('display', 'none'); }
});

Here's a JSFIDDLE , of what I have:

You've got it a tad wrong, your if statement isn't actually looking at the element which was clicked. Try something along these lines:

$('.menuitem').click(function () {
    // $(this) is a reference to  the element which was clicked
    if ($(this).attr('is-checked') == "true") 
        $('.element').css('display', 'block');
    if ($(this).attr('is-checked') == "false")
        $('.element').css('display', 'none');
});

 $('.menuitem').click(function() { console.log($(this).text().trim()) if ($(this).text().trim() === "Button 2") { if ($(this).attr('is-checked') == 'true') { $('.element').css('display', 'block'); } else { $('.element').css('display', 'none'); } } }); 
 .items { height: 30px; margin-bottom: 5px; } .menuitem { float: left; margin-right: 10px; border: 1px solid; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="items"> <div class="menuitem" is-checked="true"> <div class="ytp-menuitem-label">Button 1</div> </div> <div class="menuitem" is-checked="false"> <div class="ytp-menuitem-label">Button 2</div> </div> </div> <div class="element">some content</div> <div class="element">some more content</div> <div class="element">even more content</div> 

  1. Use $(this).attr('is-checked') to get the value
  2. Also use $(this).text().trim() to get the text of clicked element

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