简体   繁体   English

JavaScript:匹配字符串后返回锚标记

[英]JavaScript: Return anchor tag after string is matched

I am trying to return and capture in a variable the next immediate anchor tag of the string that is matched. 我试图返回并在变量中捕获匹配的字符串的下一个立即锚标记。 I want to only get the single anchor tag following the matched string and nothing else. 我只想在匹配的字符串后面得到单个锚标签,而没有别的。 This is where I am stuck. 这就是我卡住的地方。 Here is the code and jsfiddle. 这是代码和jsfiddle。

<body>

<p id="demo">Click the button to display the matches.</p>
<p><strong>Regular Edition of 325</strong></p>
<a href="link1.html">Link 1</a>
<p><strong>Regular Edition of 658</strong></p>
<a href="link2.html">Link 2</a>
<p><strong>Regular Edition of Something Else</strong></p>
<a href="link3.html">Link 3</a>
<p></p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction(){
parseIt = $("p").find("strong").text();
matchIt();
}
function matchIt(){
resIt = parseIt.match(/Regular Edition of 325/);
document.getElementById("demo").innerHTML=resIt;
console.log($(resIt));
}

</script>

</body>

http://jsfiddle.net/pbpyrojust/V86t6/6/ http://jsfiddle.net/pbpyrojust/V86t6/6/

Any help is greatly appreciated. 任何帮助是极大的赞赏。 Also let me know if you need more information. 如果您需要更多信息,也请告诉我。

You can use .filter to get the p element via the matched text: 您可以使用.filter通过匹配的文本获取p元素:

function myFunction(){
    parseIt = $("p").find("strong");
    matchIt();
}
function matchIt(){
    resIt = parseIt.filter(function () {
        return $(this).text().match(/Regular Edition of 325/);
    });
    document.getElementById("demo").innerHTML= resIt.parent().next().text();
}

http://jsfiddle.net/V86t6/7/ http://jsfiddle.net/V86t6/7/


Side note: don't communicate between functions via global variables. 注意:不要通过全局变量在函数之间进行通信。 Each function should just be using its own local variables or closed-over variables. 每个函数应仅使用其自己的局部变量或封闭变量。

I used this: 我用这个:

$('button').click(function() {
    $('p.search').each(function() {
        if(this.innerHTML.match(/Regular Edition of 325/)) {
            var $link = $(this).next('a');
            $('#demo').text($link.text());
            console.log($link);
        }
    });
});

On button click, it loops through every element you want to search. 单击按钮时,它将遍历您要搜索的每个元素。 If the elements contents match the regex, then we find the next link. 如果元素内容与正则表达式匹配,则找到下一个链接。 After this, you can do anything with the link. 之后,您可以使用链接执行任何操作。

JSFiddle 的jsfiddle


UPDATE: 更新:

Here is a pure-JS version. 这是纯JS版本。 Note, that this is only compatible with IE 9+ because of my use of document.getElementsByClassName() . 请注意,由于我使用document.getElementsByClassName() ,因此仅与IE 9+兼容。

document.getElementById('trigger').addEventListener('click', function() {
    var paragraphs = document.getElementsByClassName('search');
    for(var i = 0; i < paragraphs.length; i++) {
        var paragraph = paragraphs[i];
        if(paragraph.innerHTML.match(/Regular Edition of 325/)) {
            var link = paragraph.nextSibling;
            while(link) {
                if(link.tagName === 'A') {
                    document.getElementById('demo').innerHTML = link.innerHTML;
                    console.log(link);

                    break;
                }

                link = link.nextSibling;
            }
        }
    }
});

JSFiddle 的jsfiddle

You can simplify this a lot by doing something like this: 您可以通过执行以下操作来简化此操作:

function myFunction() {
    parseIt = $("p strong").filter(function () {
        return this.innerText.match(/Regular Edition of 325/);
    });
    var anchor = parseIt.parent().next("a");
}

http://jsfiddle.net/V86t6/9/ http://jsfiddle.net/V86t6/9/

If you want an attribute from the anchors, then it's easier to loop through the "a" tags instead of the paragraph nodes. 如果需要锚点的属性,则遍历“ a”标签而不是段落节点会更容易。 You can use jQuery's "prev()" method to access the preceding "p" and check that its text matches your regex. 您可以使用jQuery的“ prev()”方法访问前面的“ p”并检查其文本是否与您的正则表达式匹配。 http://jsfiddle.net/V86t6/13/ http://jsfiddle.net/V86t6/13/

function myFunction(){
  var mtch = new RegExp(/Regular Edition of 325/);
  $('a').each(function () {
    if($(this).prev().find("strong").text().match(mtch)) {
      document.getElementById("demo").innerHTML=$(this).attr("href")
    }
  });
}

Note that this code will break if the html changes. 请注意,如果html更改,则此代码将中断。 Consider wrapping each label/link in a div and iterating over the containers rather than traversing using prev/next/closest, etc. 考虑将每个标签/链接包装在div中并遍历容器,而不是使用prev / next / closest等遍历。

Since a pure JS version was called for ( http://jsfiddle.net/V86t6/15/ ): 由于需要使用纯JS版本( http://jsfiddle.net/V86t6/15/ ):

function myFunction(){
  var mtch = /Regular Edition of 325/;
  Array.prototype.forEach.call(
    document.querySelectorAll('p strong'),
    function(strong) {
      if(strong.innerHTML.match(mtch))
        document.getElementById("demo").innerHTML = strong.parentNode.nextElementSibling.href;
    }
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM