jQuery 中的 JS 变量

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

我有 jQuery 代码,需要通过更改索引重复它 4 次。 所以我使用了 JS 的 for 循环并在内部获取 jQuery 代码。

我使用正确的方法将变量从 JS 传递到 jQuery 吗? 它应该选择父元素的 .info-btn 元素:#info-box-pr-1、#info-box-pr-2、...

jQuery(document).ready(function() {
  for (let i = 1; i < 5; i++) {
    jQuery("#info-box-pr-" + i + ".less-info-box .info-btn").click(function() {
      jQuery("#info-box-pr-" + i + ".more-info-box").css("display", "block");
    });

    jQuery("#info-box-pr-" + i + ".more-info-box .info-btn").click(function() {
      jQuery("#info-box-pr-" + i + ".more-info-box").css("display", "none");
    });
  }
});
javascript
2个回答
0
投票

jQuery 是一个依赖于 Javascript 的框架,因此您无需在它们之间传递变量。您只需将

i
值连接到一个字符串,这很好。

话虽这么说,我建议避免增量

id
属性,因为它会导致代码变得不必要的复杂性。

例如,您可以删除循环和

id
,并通过使用通用类名和 DOM 遍历方法(例如
closest()
next()
prev()
)来关联
.info-btn
,从而使代码具有无限可扩展性。到
.more-info-box

jQuery($ => {
  $('.less-info-box .info-btn').on('click', e => $(e.target).closest('.less-info-box').hide().next().show());
  $('.more-info-box .info-btn').on('click', e => $(e.target).closest('.more-info-box').hide().prev().show());
});
.more-info-box { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="less-info-box">
  Less info
  <button class="info-btn">More</button>
</div>
<div class="more-info-box">
  More information...
  <button class="info-btn">Less</button>
</div>

<div class="less-info-box">
  Less info
  <button class="info-btn">More</button>
</div>
<div class="more-info-box">
  More information...
  <button class="info-btn">Less</button>
</div>

<div class="less-info-box">
  Less info
  <button class="info-btn">More</button>
</div>
<div class="more-info-box">
  More information...
  <button class="info-btn">Less</button>
</div>


0
投票

你并不真的需要 jQuery 来实现这个。使用事件委托来处理文档级别的事情。例如:

document.addEventListener(`click`, handle);

function handle(evt) {
  if (evt.target.id.startsWith('info-box')) {
    // hide all div#more-...
    document.querySelectorAll(`.more`).forEach(m => m.classList.add(`hidden`));
    // display the div with id #more-[id of the clicked button]
    document.querySelector(`#more-${evt.target.id}`).classList.remove(`hidden`);
  }
}
.hidden {
  display: none;
}
<button id="info-box-pr-1">info 1</button>
<button id="info-box-pr-2">info 2</button>
<button id="info-box-pr-3">info 3</button>

<div id="more-info-box-pr-1" class="more hidden">more infobox 1</div>
<div id="more-info-box-pr-2" class="more hidden">more infobox 2</div>
<div id="more-info-box-pr-3" class="more hidden">more infobox 3</div>

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