How can I emulate jQuery's trigger()?
I have a small script I am writing (to ignore the hundreds of stupid requests I get on FaceBook).
var inputs = document
.getElementById('contentArea')
.getElementsByTagName('input');开发者_StackOverflow
for (var i = 0, inputsLength = inputs.length; i < inputsLength; i++) {
if (inputs[i].value !== 'Ignore') {
continue;
}
// What I would do with jQuery, if inputs[i] was a jQuery object.
inputs[i].click();
}
So basically I want to call the click event on all these ignore buttons, and let FaceBook's AJAX do the rest.
How can I emulate the click without jQuery? I have Googled but haven't found the answer.
.click()
is a method of HTMLInputElement
s in Firefox (not sure if in other browsers too).
Another way, that should work in other browsers too, is using document.createEvent
:
var inputs = document
.getElementById('contentArea')
.getElementsByTagName('input');
for (var i = 0, inputsLength = inputs.length; i < inputsLength; i++) {
if (inputs[i].value !== 'Ignore') {
continue;
}
// maybe it is enough to create it only once before the the loop, don't know
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
inputs[i].dispatchEvent(evt);
}
Of course one would capsulate this in function to make it reusable ;)
I just tried that code above (using click()
) and it worked in my Firefox.
So I guess the answer is, do it just like jQuery.
The final code is...
var inputs = document
.getElementById('contentArea')
.getElementsByTagName('input');
for (var i = 0, inputsLength = inputs.length; i < inputsLength; i++) {
if (inputs[i].name !== 'actions[reject]') {
continue;
}
inputs[i].click();
}
精彩评论