Greasemonkey更改窗体中单选按钮的值

Greasemonkey to change value of Radio buttons in a form?

本文关键字:单选按钮 窗体 Greasemonkey      更新时间:2023-09-26

我正在编写Greasemonkey/Tampermonkey脚本,需要根据单选控件的名称和值打开单选按钮。

这就是它的样子:

<input type="radio" name="11" value="XXX" class="radio">
<input type="radio" name="11" value="zzzz" class="radio">

所以我想设置那些名称为11、值为zzzz的按钮进行检查。

当您使用jQuery时,这非常容易。这是一个完整的脚本:

// ==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选择器获取具有初始zzzz的所有<input>,但前提是它们位于具有name="11"的单选按钮组中。

参考:

  • jQuery
  • jQuery选择器文档
  • jQuery .prop()

重要信息:;以上内容适用于大多数页面,但在AJAX驱动的页面上,您通常需要使用AJAX感知技术这是因为Greasemonkey脚本将在加载您关心的复选框之前运行。

处理此问题的一种方法是使用waitForKeyElements实用程序。像这样:

// ==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);
}



旧答案是"最先进的":(当问题被问到时:

// ==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");