我是初学者,正在学习如何为Tampermonkey编写代码。我知道如何使用类标记或id标记单击自动点击。但有没有可以根据数据ID,名称或图像URL等数据信息自动点击?
HTML就像:
<div class="yellow-bot" data-image="//imgurl1.gif" data-id="123" data-name="Image1">...</div>
<div class="yellow-bot" data-image="//imgurl2.gif" data-id="124" data-name="Image2">...</div>
<div class="yellow-bot" data-image="//imgurl3.gif" data-id="125" data-name="Image3">...</div>
...
...
...
<div class="submitButton">
<input id="button" type="submit" value="Submit Now" class="btn-primary">
</div>
所以我想点击单击ID 124和125,但类是完全相同的。然后单击“提交”按钮。谁能帮我这个?
参考CSS selectors和jQuery selectors。
所以,按属性选择:
document.querySelector (".yellow-bot[data-id='124']").click ();
document.querySelector (".yellow-bot[data-id='125']").click ();
或者更强大:
// ==UserScript==
// @name _Click nodes by attribute
// @match *://YOUR_SERVER.COM/YOUR_PATH/*
// @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// @grant GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.
/* global $, waitForKeyElements */
waitForKeyElements (".yellow-bot[data-id='124']", clickNode, true);
waitForKeyElements (".yellow-bot[data-id='125']", clickNode, true);
function clickNode (jNode) {
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
jNode[0].dispatchEvent (clickEvent);
}
其余的,请参阅Choosing and activating the right controls on an AJAX-driven site。