首页 > 解决方案 > 从标签中获取 href 属性

问题描述

我需要从页面中获取标签中的所有特定href属性。a我从页面中需要的所有hrefs 如下所示:

href="/46089021"

整体a看起来是这样的:

<a class="truncate openwindow" target="_blank" href="/46089021" title="Blah Blah Blah">

谢谢你的帮助。

我忘了说,那些hrefs 有唯一的数字……每个企业在斜线后面都有不同的 8 位数字。不管是js还是jquery

标签: javascriptjqueryhtml

解决方案


如果要选择<a>以 href 开头/并后跟 8 位数字的所有内容,可以使用filter()

var result = $('a').filter(function(){
    return /^\/[0-9]{8}$/.test( $(this).attr('href') );
});
	
//Print the result for testing
result.each(function(){
    console.log( $(this).attr('href') );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="truncate openwindow" target="_blank" href="not-this-one" title="Blah Blah Blah">
<a class="truncate openwindow" target="_blank" href="/46089022" title="Blah Blah Blah">
<a class="truncate openwindow" target="_blank" href="/46089023" title="Blah Blah Blah">
<a class="truncate openwindow" target="_blank" href="not-this-one-too" title="Blah Blah Blah">
<a class="truncate openwindow" target="_blank" href="/46089025" title="Blah Blah Blah">


推荐阅读