Assigning value of data- attribute to seperate html element

问题: I have been trying to build a popup menu using HTML, CSS, jQuery. I obviously don't want to have to copy blocks of code for every menu item and am using (this) with the dat...

问题:

I have been trying to build a popup menu using HTML, CSS, jQuery. I obviously don't want to have to copy blocks of code for every menu item and am using (this) with the data-* attribute to do so.
My relevant code is:

$(".source_dropdown_button").click(function() {

  var src_content = $(this).data("content");
  $(src_content).style.display = "block";

});
<p><button class="source_dropdown_button" id="ds_dropdown_button" data-content="#ds_dropdown_content">Sources: Domestic</button></p>

<div class="source_dropdown_content" id="ds_dropdown_content">

  <a href="">External/internal link 1</a>
  <a href="">External/internal link 2</a>
  <a href="">External/internal link 3</a>

</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

When I run it like this the console says that it can't assign 'display' to undefined so I replaced the lasts line with - console.log(src_content)

The console now returns the string "#ds_dropdown_content" which is the value I gave the data- attribute in my HTML while actually trying to assign the DIV with id="ds_dropdown_content" to the attribute value.

So I'm pretty sure I found my problem, I'm just short on solutions and haven't been able to find a successful answer on the internet.

Can someone please tell me: how I can assign the contents of this element to the value of my data- attribute? Thank you


回答1:

That's because $(src_content) is a jQuery object, and it does not expose the .style property like JS does for HTMLElement.

Use jQuery's .css() Method:

$(src_content).css({display: "block"});

or extract first the Element using [0] or jQuery's .get(0) before using JS's .style

$(src_content)[0].style.display = "block";

A better suggestion would be to handle the styles exclusively via CSS stylesheet,
and use JS's Element.classList.toggle() or jQuery's $().toggleClass() to toggle that one specific class:

$("[data-content]").on("click", function() {
  $(this.dataset.content).toggleClass("is-hidden");
});
/* bool helpers */
.is-hidden {
  display: none;
}
<p>
  <button
     type="button"
     class="source_dropdown_button"
     id="ds_dropdown_button"
     data-content="#ds_dropdown_content">Sources: Domestic</button>
</p>
<div class="is-hidden" id="ds_dropdown_content">
  <a href="">External/internal link 1</a>
  <a href="">External/internal link 2</a>
  <a href="">External/internal link 3</a>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

  • 发表于 2020-06-27 20:33
  • 阅读 ( 162 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除