首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在表单中更改单选按钮值的快捷键?

在表单中更改单选按钮值的快捷键?
EN

Stack Overflow用户
提问于 2011-07-01 02:21:15
回答 1查看 2.5K关注 0票数 2

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

它看起来是这样的:

代码语言:javascript
复制
<input type="radio" name="11" value="XXX" class="radio">
<input type="radio" name="11" value="zzzz" class="radio">

因此,我希望将名称为11、值为zzzz的按钮设置为选中状态。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-07-01 05:01:46

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

代码语言:javascript
复制
// ==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 selector documentation
  • jQuery .prop()

重要提示:虽然上面的方法在大多数页面上都有效,但是,在AJAX驱动的页面上,你通常需要使用AJAX感知的技术。这是因为Greasemonkey脚本会在你关心的复选框被加载之前运行。

解决这个问题的一种方法是使用the waitForKeyElements utility。如下所示:

代码语言:javascript
复制
// ==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);
}

旧答案是“最先进的”:)当问题被问到的时候:

代码语言:javascript
复制
// ==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");
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6539300

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档