Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

jquery - Tampermonkey to select a dropdown value. It has no ID or name, just a class?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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? :

  1. A click event.
  2. A value change.
  3. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...