根据特定事件强制按钮单击

时间:2013-04-27 21:43:26

标签: javascript

很抱歉,如果我的问题我不会包含太多代码,但我是Javascript新手。 我需要创建一个将从此HTML代码中获取值的脚本:

<span class="bianco" id="contatore_139287">91.5</span>

如果该值低于0.9,则javascript函数应强制单击以下按钮:

<input type="button" value="PUNTA" onclick="puntal7h5n6o1ut5ovslhtou7ii2gu6(139287);" id="bottone2139287">

它会安装在我的浏览器上,以便在特定事件发生时自动点击我自己网站上的按钮(如上所述,值低于0.9)

你可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

这是一个如何完成的例子

<强> HTML

<button id="button">Click me</button>
<span id="watch">0.0</span>

<强>的JavaScript

/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/*global */

(function () {
    "use strict";

    if (typeof window.MutationObserver !== "function") {
        window.MutationObserver = window.WebKitMutationObserver || window.MozMutationObserver;
    }

    var button = document.getElementById("button");
    var watch = document.getElementById("watch");
    var i = 87;
    var stop = 95;
    var detect = 91.5;
    var step = 0.5;
    var id;

    function click(obj) {
        var evt = document.createEvent("MouseEvents");

        evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

        return obj.dispatchEvent(evt);
    }

    function whenClicked() {
        alert("I've been clicked!");
    }

    button.addEventListener("click", whenClicked, false);

    if (typeof window.MutationObserver !== "function") {
        watch.addEventListener("DOMNodeInserted", function () {
            if (parseFloat(watch.textContent) === detect) {
                click(button);
            }
        }, false);
    } else {
        var observer = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                if (mutation.type === 'childList' && mutation.target.id === "watch" && parseFloat(mutation.target.textContent) === detect) {
                    click(button);
                }
            });
        });

        observer.observe(document, {
            childList: true,
            characterData: true,
            subtree: true
        });
    }

    id = setInterval(function () {
        i += step;
        if (i > stop) {
            clearInterval(id);

            if (typeof window.MutationObserver !== "function") {
                watch.removeEventListener("DOMNodeInserted");
            } else {
                observer.disconnect();
            }

            return;
        }

        watch.textContent = i;
    }, 1000);
}());

jsfiddle

当然,您无需以编程方式单击该按钮,只需在达到所需条件时执行按钮的功能。