我试图在变量中返回并捕获匹配字符串的下一个直接 anchor 标记。我只想获取匹配字符串后面的单个 anchor 标记,而不获取其他任何内容。这就是我被困住的地方。这是代码和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/
非常感谢任何帮助。如果您需要更多信息,也请告诉我。
最佳答案
如果您想要 anchor 的属性,那么循环遍历“a”标签而不是段落节点会更容易。您可以使用 jQuery 的“prev()”方法来访问前面的“p”并检查其文本是否与您的正则表达式匹配。 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")
}
});
}
请注意,如果 html 发生更改,此代码将会中断。考虑将每个标签/链接包装在 div 中并迭代容器,而不是使用上一个/下一个/最近的等进行遍历。
由于需要纯 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;
}
);
}
关于JavaScript:字符串匹配后返回 anchor 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22869741/