如何向具有相同类的多个元素添加事件侦听器,然后仅更改特定其他元素的 CSS

问题描述 投票:0回答:3

我基本上希望能够显示和隐藏多个文本块,彼此完全分开。这样,当按下其中一个按钮时,其正下方的相应引用就会变得可见(显示:块),但该引用。

这是我到目前为止所拥有的,但我现在已经碰壁了:

JS:

<script> 
    let btn = document.querySelectorAll('btn');
    let quote = document.querySelectorAll('quote');
    btn.addEventListener("click", function(){
        if (quote.style.display == "block") {
            quote.style.display = "none";
        } else {
            quote.style.display = "block";
        }
    });
</script>

HTML:

<button class="btn">Click here to see the quote</button>
<p class="quote">blah blah blah</p>

<button class="btn">Click here to see the quote</button>
<p class="quote">blah blah blah</p>

<button class="btn">Click here to see the quote</button>
<p class="quote">blah blah blah</p>
javascript html dom
3个回答
2
投票

您必须为循环中的每个按钮声明一个事件侦听器,并在侦听器内声明引号。我还反转了

display
属性值。

您还忘记了

btn
变量中的一个点:
let btn = document.querySelectorAll('.btn')

let btn = document.querySelectorAll('.btn');
for (i = 0; i < btn.length; i++) {
    btn[i].addEventListener('click', function () {
        let quote = this.nextElementSibling;
        console.log('quote: ', quote);
        if (quote.style.display == "none") {
            quote.style.display = "block";
        } else {
            quote.style.display = "none";
        }
    });
}
<button class="btn">Click here to see the quote</button>
<p class="quote">blah blah blah</p>

<button class="btn">Click here to see the quote</button>
<p class="quote">blah blah blah</p>

<button class="btn">Click here to see the quote</button>
<p class="quote">blah blah blah</p>


0
投票

首先,如果要选择班级,应该是

querSelectorAll('.btn')
querSelectorAll('.quote')
(以
.
开头)。

其次,使用

querSelectorAll
,您的
btn
quote
变量将是节点列表(您应该将其命名为
btns
quotes
顺便说一句),因此您将无法向其添加事件侦听器。你应该做的是迭代抛出你的列表并为每个项目添加事件监听器:

let btns = [...document.querySelectorAll('.btn');
btns.map(btn => btn.addEventListener('click', (btn, idx) => handleBtnClick(btn, idx));

然后在

handleBtnClick
中,选择对应
idx
的div并使其可见,而其他div不可见:

const handleBtnClick = (btn, idx) => {
    let quotes = [...document.querySelectorAll('.quote')];
    quotes.map( (quote, quotedIdx) => {
       if (quoteIdx === idx) {
          quote.style.display = 'block';
       } else {
          quote.style.display = 'none';
       }
    }
    

此代码未优化,请随意重构


0
投票

使用 jQuery 我做了这个:

使用您单击的按钮

$(this)
,并使用
.next()
给出下一个元素。

您可以找到下一个元素(我添加了一个检查以确保下一个元素在运行之前具有类引用)并应用您的样式

$('.btn').on('click', function() {
  if ($(this).next().hasClass('quote')) {
    $(this).next().css('display', 'block');
  }
});
p {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">Click here to see the quote</button>
<p class="quote">blah blah blah</p>

<button class="btn">Click here to see the quote</button>
<p class="quote">blah blah blah</p>

<button class="btn">Click here to see the quote</button>
<p class="quote">blah blah blah</p>

© www.soinside.com 2019 - 2024. All rights reserved.