Click on Button Class or Span class

问题: I want to simulate a click on a button up or down, I tried with this :document.querySelector('button.up')[4].click(); in the page there is few input field with up and...

问题:

I want to simulate a click on a button up or down,

I tried with this :document.querySelector('button.up')[4].click();

in the page there is few input field with up and down button, I would like the button up of the field with id "sl" or nth up button ? the code :

<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>

回答1:

The first thing that's likely to cause a problem is this line:

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

The reasons this causes a problem is that document.querySelector() returns either the first element matching the supplied selector or null, if there are no elements matching the selector. Therefore index notation the [4] is destined to fail by design.

Without seeing more of your HTML it's hard to offer a fully working suggestion, but I'd suggest that using an alternative selector should work (so long as your id attributes are unique, as they must be be according to the spec):

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>

References:

  • 发表于 2019-02-17 03:30
  • 阅读 ( 213 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除