鉴于目标页面上的此 HTML:
<dd class="ddTit">
<a href="http://abc.xxx.com/54781.html" target="_blank">special text words</a>
</dd>
如何根据“ 特殊文本词 ”获取 url,并在 Greasemonkey 脚本中单击?
我试过这个:
var textlink = document.querySelector ("dd.ddTit a[textContent*='special']");
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
textlink.dispatchEvent (clickEvent);
没有运气。
如何根据
textContent
进行选择,例如 textContent
包含单词 特殊 ? 最佳答案
唉,你不能用 querySelector()
做到这一点,因为 CSS selectors do not (yet) offer a content/text selector 。
这里有3种方法:
var ddTitLinks = document.querySelectorAll ("dd.ddTit a");
for (var J = ddTitLinks.length - 1; J >= 0; --J) {
var ddTitLink = ddTitLinks[J];
//--- Case-insensitive search.
if (/special text words/i.test (ddTitLink.textContent) ) {
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
ddTitLink.dispatchEvent (clickEvent);
break;
}
}
// ==UserScript==
// @name _Click Special link(s)
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// ==/UserScript==
//--- Note that contains() is CASE SENSITIVE.
var specLink = $("dd.ddTit a:contains('special text words')");
if (specLink.length) {
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
specLink[0].dispatchEvent (clickEvent);
}
//--- Note that contains() is CASE SENSITIVE.
var specLinks = document.evaluate (
"//dd[contains(@class, 'ddTit')]/a[contains(text(), 'special text words')]",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null
);
if (specLinks.snapshotLength) {
var specLink = specLinks.snapshotItem (0);
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
specLink.dispatchEvent (clickEvent);
}
关于javascript - 我的用户脚本如何根据链接的文本获取链接?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12375008/