我正在尝试实现用纯JavaScript编写的jQuery(下面)的等价物:
$('input[name=\"myelementname\"]').keyup();
到目前为止,我还没有找到一个简单的解决方案。有什么想法吗?
答案 0 :(得分:6)
首先,您必须创建一个新事件:
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()
。参考书目: