Greasemonkey脚本似乎不按顺序执行行

时间:2013-09-10 17:56:03

标签: javascript jquery greasemonkey

给出以下HTML:

<table class="cat_list">
<tr>
    <td>
        <input type="checkbox" name="filter_cat[1]" id="cat_1" value="1"/>
        <label for="cat_1">Music</label>
    </td>
    <td>
        <input type="checkbox" name="filter_cat[2]" id="cat_2" value="1"/>
        <label for="cat_2">Applications</label>
    </td>
    <td>
        <input type="checkbox" name="filter_cat[3]" id="cat_3" value="1"/>
        <label for="cat_3">E-Books</label>
    </td>
    <td>
        <input type="checkbox" name="filter_cat[4]" id="cat_4" value="1"/>
        <label for="cat_4">Audiobooks</label>
    </td>
    <td>
        <input type="checkbox" name="filter_cat[5]" id="cat_5" value="1"/>
        <label for="cat_5">E-Learning Videos</label>
    </td>
    <td>
        <input type="checkbox" name="filter_cat[6]" id="cat_6" value="1"/>
        <label for="cat_6">Magazines</label>
    </td>
    <td>
        <input type="checkbox" name="filter_cat[7]" id="cat_7" value="1"/>
        <label for="cat_7">Comics</label>
    </td>
</tr>

以下脚本应取消选中表格行中的所有复选框,然后选中ID为cat_1的特定复选框。

$(".cat_list input[type='checkbox']").attr("checked",false);

$("#cat_1").attr("checked",true);

在Greasemonkey中,它会检查一个框一毫秒,然后取消选中所有框。仅第二个命令单独执行时检查cat_1框,但是当你在它上面添加一行时,它们都会在...之后被取消选中。

那么,Greasemonkey是不正确地执行了什么或者是什么?看起来它正在向后运行脚本或者存在计时问题,比如它开始取消检查异步然后在取消检查完成之前完成检查。

2 个答案:

答案 0 :(得分:1)

可能是your script's jQuery and the page are conflicting。一个简单的@grant GM_addStyle就可以了。 发布完整的脚本。


否则, jQuery代码同步运行。该页面的javascript正在干扰您要执行的操作,或者该问题中忽略了某些键。

可能,您的脚本在页面完成设置之前就开始了。如果可以,请链接到实际目标页面。

分析作用于这些输入的页面的javascript,并考虑使用页面自己的JS进行更改。该页面可能需要/期望设置状态,而不仅仅是切换的复选框。

通过script injectionunsafeWindow使用页面的JS。


使用计时器,就像在psyjoniz的答案中一样,可能就足够了。也许不会。但是,这很容易尝试。我会使用更长的间隔:

$(".cat_list input[type='checkbox']").attr ("checked", false);

//-- Give the page's JS time to react and settle.
setTimeout ( function () { $("#cat_1").attr ("checked", true); }, 100);

答案 1 :(得分:0)

试试这个..

setTimeout(function(){$("#cat_1").attr("checked",true);},0);

如果是某种竞争条件,这会将你的命令放在堆栈的底部。

相关问题