如何根据图像源单击“回答”链接?

时间:2012-10-03 22:55:48

标签: javascript click greasemonkey

我有一个简单的“谁是”游戏页面,我想用Greasemonkey制作一个简单的自动回答脚本。我该怎么做?

基于图片sid中的src

<img src="whois_picture.php?yid=123456&sid=3084" />

应该点击匹配的链接......

  • 如果sid=3084,请选择回答d
  • 如果sid=3023,请选择回答a

模拟:http://thedudu.com/auto_select/

关键目标页面HTML:

<div id="whois_guestion">
    <img src="whois_picture.php?yid=123456&sid=3084" />
</div>
<div id="game_options">
    <a href="#" class="game_option">Mickey Mouse</a>
    <input type="hidden" value="a" name="secenekharf" />

    <a href="#" class="game_option">Bugs Bunny</a>
    <input type="hidden" value="b" name="secenekharf" />

    <a href="#" class="game_option">Gofy</a>
    <input type="hidden" value="c" name="secenekharf" />

    <a href="#" class="game_option">Mario</a>
    <input type="hidden" value="d" name="secenekharf" />
</div>

1 个答案:

答案 0 :(得分:0)

  1. 创建sid s的对象并回答,如下:

    var answerKey   = {
          3084: "d"
        , 3023: "a"
        //etc.
    };
    
  2. 然后使用jQuery选择正确的答案链接。

  3. 最后,发送链接点击事件。

  4. 以下是完整脚本的外观:

    // ==UserScript==
    // @name     _Auto-answer script
    // @include  http://thedudu.com/auto_select/*
    // @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.
    */
    
    var answerKey   = {
          3084: "d"
        , 3023: "a"
        //etc.
    };
    
    setTimeout (clickAnswerIfAny, 222); //-- 222 milliseconds
    
    function clickAnswerIfAny () {
        var questImg    = $("#whois_guestion img");
        var questSid    = questImg.attr ("src").replace (/^.+?\bsid=(\d+).*$/i, "$1");
        var answerVal   = answerKey[questSid];
        if (typeof answerVal != "undefined") {
            console.log ("Ans found...");
            //-- Find the <input> with the answer value.
            var answerInp   = $("#game_options input[value='" + answerVal + "']");
            if (answerInp.length) {
                //-- In this case, the link is the previous sibling element.
                var answerLink  = answerInp.prev ();
                console.log (answerInp, answerLink);
                //-- Click the link.
                console.log ("Clicking...");
                var clickEvent  = document.createEvent ('MouseEvents');
                clickEvent.initEvent ('click', true, true);
                answerLink[0].dispatchEvent (clickEvent);
            }
        }
    }
    


    另见this answer