简体   繁体   中英

Using .addClass on data-attribute elements with specific values

I'm trying to create a modal popup system in jQuery, that keeps the code as simple as possible. I've looked up tutorials on this, but they all only ever show it working with one modal in the HTML. If I have multiple modals on the page with the attribute data-popup, how can I make only the one selected popup?

Here's my current attempt:

$("[data-popupBtn]").click(function() {
  if ($("[data-popupBtn='schedule']")) {
    $("[data-popup='schedule']").addClass("visible");
    $(".popup-bg").addClass("visible");
  } else {
    if ($("[data-popupBtn='booklet']")) {
      $("[data-popup='booklet']").addClass("visible");
      $(".popup-bg").addClass("visible");
    } else {
      null
    }
  }
})

With the HTML being:

<div class="popup-bg">

  <div class="popup" data-popup="schedule">
    <a class="popup-x">&times;</a>
    <div>
      <p>CONTENT</p>
    </div>
  </div>

  <div class="popup" data-popup="booklet">
    <a class="popup-x">&times;</a>
    <div>
      <p>CONTENT</p>
    </div>
  </div>

</div>

My goal in this was to create triggers that can be used anywhere on the page, as many times as I want with a simple data-popupBtn="insertPopupType" in the element. The code I currently have works flawlessly for making the data-popup="schedule" popup... but the jQuery seems to fail when checking the if ($("[data-popupBtn='schedule']")) vs the if ($("[data-popupBtn='booklet']")) . If you have a better way of incorporating multiple modal popups on a single page, let me know.

<a class="btn" data-popup="schedule">Button for Schedule</a>
<a class="btn" data-popup="schedule">Button for Schedule</a>
<div class="popup-bg">

 <div class="popup" data-popup="schedule">
   <a class="popup-x">&times;</a>
  <div>
  <p>CONTENT Schedule</p>
</div>
</div>


<div class="popup" data-popup="booklet">
<a class="popup-x">&times;</a>
<div>
  <p>CONTENT</p>
</div>
</div>

</div>
$("[data-popup]").click(function() {
$(".popup-bg").addClass("visible");
$('[data-popup='+$(this).data('popup')+']').addClass('visible')

})

Louys Patrice Bessette answered my question in a comment! Thanks!

"Unclear how you can click on a "popup" that is not "visible"... But for sure, the condition if ($("[data-popupBtn='schedule']")) will always be true if the element exist in the page. -- Maybe you will be interested in jQuery.is() and make a condition like if ($(this).is($("[data-popupBtn='schedule']")) . Try it and if you still have problems, please make sure you provide everything to reproduce the issue." – Louys Patrice Bessette Dec 10 at 17:54

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