问题描述
我正在编写一个Greasemonkey/Tampermonkey脚本,我需要根据单选控件的名称和值打开单选按钮.
I am writing a Greasemonkey/Tampermonkey script and I need to turn on radio buttons depending on the name and value of the radio control.
这是它的外观:
<input type="radio" name="11" value="XXX" class="radio">
<input type="radio" name="11" value="zzzz" class="radio">
所以我想设置名称为11且值为zzzz的按钮进行检查.
So I want to set those buttons that have name of 11 and a value of zzzz to be checked.
推荐答案
使用jQuery时,这非常容易.这是一个完整的脚本:
This is super easy when you use jQuery. Here's a complete script:
// ==UserScript==
// @name _Radio button check
// @include http://YOUR_SITE/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
$("input[name='11'][value='zzzz']").prop ('checked', true);
input[name='11'][value='zzzz']
jQuery选择器将获取所有具有 initial 值zzzz
的<input>
,但前提是它们位于带有name="11"
的单选按钮组中.
The input[name='11'][value='zzzz']
jQuery selector gets all <input>
s that have the initial value zzzz
, but only if they are in the group of radio buttons with name="11"
.
参考:
- jQuery
- jQuery selector documentation
- jQuery
.prop()
重要提示: 上面的代码适用于大多数页面,但是在AJAX驱动的页面上,您经常需要使用AJAX感知技术.因为这是因为Greasemonkey脚本将在您选中该复选框之前运行关心已加载.
Important: The above works on most pages but, on AJAX-driven pages, you often need to use AJAX-aware techniques. This is because the Greasemonkey script will run before the checkbox you care about is loaded.
一种解决方法是使用 waitForKeyElements
实用程序.像这样:
One way to deal with this is with the waitForKeyElements
utility. Like so:
// ==UserScript==
// @name _Radio button check
// @include http://YOUR_SITE/YOUR_PATH/*
// @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 work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
waitForKeyElements ("input[name='11'][value='zzzz']", selectRadioButton, true);
function selectRadioButton (jNode) {
jNode.prop ('checked', true);
}
原来的答案是最新技术" :),当有人问到问题时:
Old answer that was "state of the art" :) back when the question was asked:
// ==UserScript==
// @name _Radio button check
// @include http://YOUR_SITE/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
// ==/UserScript==
$("input[name='11'][value='zzzz']").attr ("checked", "checked");
这篇关于Greasemonkey可以更改表单中单选按钮的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!