简体   繁体   English

控制 id 与 javascript 中的 href 匹配的元素

[英]Control an element whose id matches with href in javascript

I am trying to achieve a simple show/hide content by clicking outside of some links.我正在尝试通过单击某些链接外部来实现简单的显示/隐藏内容。 I can achieve it with jQuery .我可以用 jQuery 来实现它 But, I am struggling to achieve that with vanilla javascript.但是,我正在努力使用香草 javascript 来实现这一目标。 Basically, I get the id from a like this way:基本上,我a这样的方式获取 id:

const id = e.target.getAttribute('href');

Now, I want to work with that id , but I can't.现在,我想使用那个id ,但我不能。 So, my problem is in this line:所以,我的问题出在这一行:

id.classList.remove('hidden');

My demo:我的演示:

 const texts = document.querySelectorAll('.content p > span'); const links = document.querySelectorAll('.link-block a'); links.forEach(el => { el.addEventListener('click', e => { texts.forEach(text => text.classList.add('hidden')); const id = e.target.getAttribute('href'); //console.log(id); id.classList.remove('hidden'); }); });
 .hidden { display: none; }
 <section> <section class="content"> <p> <span id="content-1">Sample Text for Content 1.</span> <span id="content-2" class="hidden">Sample Text for Content 2.</span> <span id="content-3" class="hidden">Sample Text for Content 3.</span> </p> </section> <section class="link-block"> <a href="#content-1">Content 1</a> <a href="#content-2">Content 2</a> <a href="#content-3">Content 3</a> </section> </section>

The id value is a string, not an element. id值是一个字符串,而不是一个元素。 But that string can be used with document.querySelector to find that element.但是该字符串可以与document.querySelector一起使用来查找该元素。 For example:例如:

 const texts = document.querySelectorAll('.content p > span'); const links = document.querySelectorAll('.link-block a'); links.forEach(el => { el.addEventListener('click', e => { texts.forEach(text => text.classList.add('hidden')); const id = e.target.getAttribute('href'); //console.log(id); document.querySelector(id).classList.remove('hidden'); }); });
 .hidden { display: none; }
 <section> <section class="content"> <p> <span id="content-1">Sample Text for Content 1.</span> <span id="content-2" class="hidden">Sample Text for Content 2.</span> <span id="content-3" class="hidden">Sample Text for Content 3.</span> </p> </section> <section class="link-block"> <a href="#content-1">Content 1</a> <a href="#content-2">Content 2</a> <a href="#content-3">Content 3</a> </section> </section>

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

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