问题
I'm writing a Tampermonkey code for a webpage like ConverTo:
It's supposed to automatically select the second option in a dropdown:
<select class="format-select">
<option value="mp3">MP3</option>
<option value="mp4">MP4 (video)</option>
</select>
, several seconds after the page is fully loaded.
But nothing happens.
My code:
......
// @match https://www.converto.io/*
// @require http://code.jquery.com/jquery-1.11.0.min.js
// ==/UserScript==
$(document).ready(function(){
setTimout(test(),10000);
function test()
{
$(".format-select").val('mp4');
}
})();
Please help!
回答1:
See Choosing and activating the right controls on an AJAX-driven site.
Many AJAX-driven controls cannot just be changed; they also must receive key events, for the page to set the desired state.
In the ConverTo case, that select appears to expect‡ :
- A click event.
- A value change.
- A change event.
You would send that sequence with code like this complete, working script:
// ==UserScript==
// @name _ConverTo, Automatically select mp4
// @match https://www.converto.io/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.
waitForKeyElements (".format-select:has(option[value=mp4])", selectFinickyDropdown);
function selectFinickyDropdown (jNode) {
var evt = new Event ("click");
jNode[0].dispatchEvent (evt);
jNode.val('mp4');
evt = new Event ("change");
jNode[0].dispatchEvent (evt);
}
‡ There are other state sequences possible, to the same end.
来源:https://stackoverflow.com/questions/41421019/tampermonkey-to-select-a-dropdown-value-it-has-no-id-or-name-just-a-class