-2

<h2>我正在编写一个 Greasemonkey 脚本,它应该做一件简单的事情:如果元素(页面上总是只有一个)和<h3>元素的第一次出现(可以是其中几个或根本没有)之间存在某个字符串,然后......(我已经完成了这部分)。

对于有条件的帮助,我将不胜感激。

4

4 回答 4

2
var masterString = document.body.innerHTML;
var start = masterString.indexOf('<h2>'); 
var end = masterString.indexOf('<h3>'); // Will find the position of first occurance of h3 - if any

if (end <0)
// there is no h3
else {
  var searchMe = masterString.substr(start,end);  // now this is the portion of your HTML body that you want to look for a string match
  var numberOfOccurances = searchMe.match(/yourString/g);
}
于 2012-10-08T16:05:28.613 回答
2

现在我恰好熟悉 Mikhail 正在编写的代码。

基本结构是

<div>
<div>
<h2>Something</h2>
<td>We want to search for the string here</td>
<td>We want to search for the string here</td>
</div>

<div>
<h3>Something else</h3>
<td>May contain the same string, but we are only interested if it contains in previous div .</td>
<td>May contain the same string, but we are only interested if it contains in previous div .</td>
</div>
</div>

该字符串不是 h2 的子项,因此我认为 getElementsByTagName 不会起作用。不幸的是,实际上有数百个具有相同类 ID 的 div 层。在这种特殊情况下,标题是代码中唯一的唯一细节。所以在我看来,最好的方法是先找到 h2,去它的父级并将文本存储为字符串。然后在文本中搜索字符串。像这样的...

<script>
var searcharea = jQuery('h2').parent('div').text();
var searchstring = "superstring";
if( searcharea.indexOf( searchstring ) != -1 )
    alert("exchange alert to your own things");
</script>

至于h3,它可能存在也可能不存在,但由于它不是兄弟,所以这并不重要。:) 感谢大家抽出宝贵时间回答我们的问题。

于 2012-10-08T21:36:49.617 回答
0

你试过getElementsByTagName吗?

于 2012-10-08T15:56:10.793 回答
0
//get all the H2 elements
var h2 = document.getElementsByTagName("h2");

//Just in case there are more than one...
for(var i = 0; i < h2.length; i++){
 //check for the certain string
 if(h2[i].textContent == "SOME TEXT"){
  //get the first h3 element and do something...
  var h3 = document.getElementsBtTagName("h3")[0]; //first occurrence of H3
  //DO SOMETHING
}

https://developer.mozilla.org/en-US/docs/DOM/Node.textContent

https://developer.mozilla.org/en-US/docs/DOM/element.getElementsByTagName

于 2012-10-08T16:02:12.233 回答