问题:
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: