3

我正在尝试修改下面的脚本以单击站点上如下所示的按钮:

<button id="checkPrice-02070" onclick="checkPrice(02070,null); return false;" class="orangeDark">
  <span>check price</span>
</button>

我正在使用下面的代码。到目前为止,页面似乎一直在重新加载;没有其他事情发生。
对新人有什么建议吗?

(function () {
    window.addEventListener("load", function (e) {
        clickConfirmButton()
    }, false);
})();

function clickConfirmButton() {
    var buttons = document.getElementsByTagName('button');
    var clicked = false;
    for (var index = 0; (index < buttons.length);  index++) {
        if (buttons[index].value == "check price") {
            buttons[index].click();
            clicked = true;
            break;
        }
    }
    if (!clicked) {
        setTimeout("window.location.reload()", 300 * 1000);
    }
}
4

1 回答 1

0

A <button>svalue不是可见文本。你想搜索textContent.

然而:

  1. 如果该示例 HTML 是正确的,您最好搜索以checkPrice. 请参阅下面的代码。

  2. 如果找不到按钮,您确定要重新加载吗?如果它是由 AJAX 添加的,这不是最好的方法。看到这个答案

  3. 不要setTimeout与这样的字符串(评估)参数一起使用。请参阅下面的代码。

  4. 您不需要将代码包装在匿名函数中。

无论如何,这应该工作,给定示例 HTML:

window.addEventListener ("load", clickConfirmButton, false);

function clickConfirmButton (zEvent) {
    var button = document.querySelector ("button[id^='checkPrice']");
    if (button) {
        button.click ();
    }
    else {
        setTimeout (function () { location.reload(); }, 300 * 1000);
    }
}


要检查按钮文本,请使用:

function clickConfirmButton (zEvent) {
    var buttons = document.querySelectorAll ("button[id^='checkPrice']");
    var clicked = false;

    for (var index = 0, numBtn = buttons.length;  index < numBtn;  ++index) {
        if (/check price/i.test (buttons[index].textContent) ) {
            buttons[index].click();
            clicked = true;
            break;
        }
    }
    if (!clicked) {
        setTimeout (function () { location.reload(); }, 300 * 1000);
    }
}
于 2012-06-20T06:12:11.483 回答