0
我想实现jQuery的(下图)写在普通的JavaScript等价的:触发KeyUp事件在Javascript
$('input[name=\"myelementname\"]').keyup();
我一直没能找到一个简单的解决方案迄今。有任何想法吗?
我想实现jQuery的(下图)写在普通的JavaScript等价的:触发KeyUp事件在Javascript
$('input[name=\"myelementname\"]').keyup();
我一直没能找到一个简单的解决方案迄今。有任何想法吗?
首先,你必须创建一个新的事件:
let keyupEvent = new Event('keyup');
然后用EventTarget.dispatchEvent()
:
// here we use Array.from() to convert the NodeList
// returned from the document.getElementsByNames...
// call into an Array:
Array.from(
// document.getElementsByName() retrieves all the
// elements on the page with the supplied name:
document.getElementsByName('myelementname')
// we iterate over that Array using Array.prototype.forEach():
).forEach(
// here we use an Arrow function, the 'input' is a reference
// to the current element (regardless of element-type, since
// we selected by name) of the Array-element of the Array
// over which we're iterating.
// we trigger the named event (using a cached copy of that
// created Event) on the element:
input => input.dispatchEvent(keyupEvent)
);
参考文献:
Array.from()
。Array.prototype.forEach()
。EventTarget.dispatchEvent()
。参考书目:
[闪光在JavaScript键盘事件(https://stackoverflow.com/questions/961532/firing-a - 键盘事件式的JavaScript) –