我正在为类似 ConverTo 的网页编写 Tampermonkey 代码:
它应该自动选择下拉列表中的第二个选项:
<select class="format-select">
<option value="mp3">MP3</option>
<option value="mp4">MP4 (video)</option>
</select>
,页面完全加载后几秒钟。
但什么也没发生。
我的代码:
......
// @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');
}
})();
请帮忙!
最佳答案
参见Choosing and activating the right controls on an AJAX-driven site .
许多 AJAX 驱动的控件不能简单地更改;他们还必须接收按键事件,以便页面设置所需的状态。
在ConverTo情况下,该选择似乎期望‡:
- 点击事件。
- 值发生变化。
- 变更事件。
您可以使用像这样完整的工作脚本这样的代码发送该序列:
// ==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);
}
<小时/>
‡为了同一目的,还有其他可能的状态序列。
关于jquery - Tampermonkey 选择下拉值。它没有 ID 或名称,只有一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421019/