自动单击单选按钮,但首先检查句子(标签)?

时间:2012-11-11 12:05:51

标签: javascript html radio-button greasemonkey

我需要帮助...... 我想自动点击一个单选按钮...但还需要检查句子(标签)...... 例如...()< -radio button

<label>How much is 1+1?</label><br/>
<input type="radio" name="group1" value="2"/>()2<br/>
<input type="radio" name="group1" value="3"/>()3<br/>
<input type="radio" name="group1" value="4"/>()4

我尝试过使用这个脚本:

// ==UserScript==
// @name script
// @description Auto select rpt radio button
// @include *
// ==/UserScript==

if(radio=document.evaluate('//input[@type="radio" and @value="2"]',document,null,9,null).singleNodeValue)
radio.checked=true;

好的,这段代码......点击答案()2 但如果我有以下内容会发生什么:

<label>How much is 1+1?</label><br/>
<input type="radio" name="group1" value="2"/>()2<br/>
<input type="radio" name="group1" value="3"/>()3<br/>
<input type="radio" name="group1" value="4"/>()4

How much is 4+2?<br/>
<input type="radio" name="group1" value="8"/>()8<br/>
<input type="radio" name="group1" value="2"/>()2<br/>
<input type="radio" name="group1" value="6"/>()6

没有任何事情发生,因为有两个值称为“2”..所以我试图修改代码,先检查句子,然后标记答案(但我还没有很好地掌握它)...

if(label=document.evaluate('//label[@value="How much is 1+1?"]',document,null,9,null).singleNodeValue)&&(radio=document.evaluate('//input[@type="radio" and @value="2"]',document,null,9,null).singleNodeValue)
radio.checked=true;

我的意图是添加第二个条件,检查标签的值是否包含“多少是1 + 1?”

有人可以指导我如何做到这一点吗?

编辑: 示例链接: Google docs form

页面代码如下所示: 标签:

<label class="ss-q-title" for="entry_0">How much is 1+1
<span class="ss-required-asterisk">*</span></label>

收音机:

<ul class="ss-choices"><li class="ss-choice-item"><label class="ss-choice-label"><input name="entry.0.group" value="2" class="ss-q-radio" id="group_0_1" type="radio">
2</label></li> <li class="ss-choice-item"><label class="ss-choice-label"><input name="entry.0.group" value="3" class="ss-q-radio" id="group_0_2" type="radio">
3</label></li> <li class="ss-choice-item"><label class="ss-choice-label"><input name="entry.0.group" value="4" class="ss-q-radio" id="group_0_3" type="radio">
4</label></li>
</ul>

1 个答案:

答案 0 :(得分:0)

您必须找到与您关注的<lable>(或文本节点)的兄弟姐妹最近的单选按钮。

jQuery使这种事情变得更容易,请参阅the jQuery documentation,尤其是the Selectors sectionthe Traversing section

这是一个完整的Greasemonkey脚本,它将根据问题中的新HTML(链接的Google文档)选择正确的按钮:

// ==UserScript==
// @name        YOUR_SCRIPT_NAME
// @description Auto select rpt radio button
// @include     http://YOUR_SERVER.COM/YOUR_PATH/*
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/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.
*/
//-- Note that :contains() is case-sensitive
var questionLabel   = $(
    "label.ss-q-title:contains('How much is 1+1') ~ ul.ss-choices"
).first ().find ("input[type=radio][value=2]");
questionLabel.prop ('checked', true);


您还可以See the code in action at jsFiddle.