【问题标题】:Click on Button Class or Span class单击按钮类或跨度类
【发布时间】:2019-07-09 17:10:52
【问题描述】:

我想模拟一个按钮向上或向下的点击,

我试过这个:document.querySelector('button.up')[4].click();

在页面中很少有带有向上和向下按钮的输入字段,我想要 id 为“sl”的字段的向上按钮还是第 n 个向上按钮? 代码:

<div class="input-text num" >
<input type="text" placeholder="" id="sl" min="0" max="" step="0.00001">
<button tabindex="-1" class="up">
<span class="v"></span></button><
button tabindex="-1" class="down">
<span class="v"></span></button></div>

【问题讨论】:

  • sl是输入字段的id,但是侧面有上下按钮
  • 其他有上下按钮的输入框很少,我想点击sl输入的上按钮
  • 我编辑了这个问题,谢谢

标签: javascript class button click


【解决方案1】:

可能导致问题的第一件事是这一行:

document.querySelector('button.up')[4].click();

导致问题的原因是document.querySelector() 返回匹配提供的选择器的第一个元素或null,如果没有匹配选择器的元素。因此,[4] 的索引符号注定会因设计而失败。

如果没有看到更多的 HTML,很难提供一个完全有效的建议,但我建议使用替代选择器应该可以工作(只要你的 id 属性是唯一的,因为它们必须符合规范):

document.querySelector('#sl + button.up').click();

const clickHandler = (event) => {
  console.log(`${event.target.outerHTML}`);
}

document.querySelectorAll('button').forEach(
  (button) => button.addEventListener('click', clickHandler)
);

document.querySelector('#sl + button.up').click();
<div class="input-text num">
  <input type="text" placeholder="" id="sl" min="0" max="" step="0.00001">
  <button tabindex="-1" class="up">
<span class="v">up</span></button>
  <button tabindex="-1" class="down">
    <span class="v">down</span></button>
</div>

参考资料:

【讨论】:

  • "Without see *more of your HTML*" 而不是 "Without *all of your HTML*" - 代码应始终简化为"minimal reproducible example" 原则,并发布in您的问题,而不是(仅)链接到它。
  • 谢谢,我展示的代码还不是全部,我以为就够了,其余代码都是一样的,只是id和字段不同,一个接一个
  • 我试过这个:document.querySelector('#sl + button.up').click();它不起作用可能与 span.v 而不是 button..up 一起使用吗?
  • 它不起作用” - 我不知道。在您的问题中发布您的 *minimal reproducible example" HTML,也许我们可以看到它为什么不起作用。您可能还需要先阅读“How to Ask”指南编辑您的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 2014-07-22
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多