简体   繁体   English

JavaScript-查找与数据属性值匹配的ID

[英]JavaScript - Find ID that matches data attribute value

I have a variable that finds the data attribute of an element that is clicked on in a callback function: 我有一个变量,可找到在回调函数中单击的元素的数据属性:

var dropdown = document.getElementsByClassName('js-dropdown');

 for (i = 0; i < dropdown.length; i++) {

   dropdown[i].addEventListener("click", callBack (dropdown[i]));

 }

function callBack (i) {

 return function () {

  var thisDropdown = i.getAttribute('data-dropdown');

  //rest of the code here

  }

}

I am basically trying to do this 我基本上是想这样做

$('#' + thisDropdown ).toggleClass('is-active');

...but in vanilla JS. ...但是使用香草JS。

This works fine using jQuery however I would like a vanilla version. 使用jQuery可以正常工作,但是我想要一个普通版本。

So when a user clicks on an element that activates a drop down, I want it to dynamically find its relevant ID matching value within the document so it can toggle a show/hide class. 因此,当用户单击激活下拉菜单的元素时,我希望它在文档中动态找到其相关的ID匹配值,以便它可以切换显示/隐藏类。

I've searched through a lot of SO questions and everyone replies with a jQuery answer which is not what I am looking for. 我搜索了很多SO问题,每个人都回答一个jQuery答案,这不是我想要的。

I've been trying to do something along the lines of 我一直在尝试做一些类似的事情

var idValue = document.getElementById(thisDropdown);

Then 然后

var findId= idValue + thisDropdown;

findId.toggleClass('is-active');

Obviously that does not work the same way the jQuery statement works... any ideas? 显然,这与jQuery语句的工作方式不同...有什么想法吗?

Ignore the toggleClass method! 忽略toggleClass方法! Some of you may find this contradictory as I want vanilla JS. 某些人可能会因为我想要香草JS而发现这种矛盾。

To replace $('#' + thisDropdown ).toggleClass('is-active'); 替换$('#' + thisDropdown ).toggleClass('is-active'); with plain js, use Element.classList . 对于纯js,请使用Element.classList Like this: 像这样:

const someElement = document.querySelector('#' + thisDropdown);
someElement.classList.toggle("is-active");

I like @kamyl's answer, but you might need backward compatibility. 我喜欢@kamyl的答案,但您可能需要向后兼容。 For that, see if you can find a polyfill. 为此,请查看是否可以找到一个polyfill。

If you have to write it yourself, use string.split(" ") to get your list of active attributes and iterate to find if it exists; 如果必须自己编写,请使用string.split(" ")获取活动属性列表,并进行迭代以查找是否存在; add if not, remove if so...then array.join(" ") and replace the class attribute with it. 如果不是,则添加;如果是,则删除...然后, array.join(" ")并将其替换为class属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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