繁体   English   中英

获取具有特定href属性的元素数组

[英]get array of elements having specific href attribute

我需要一些元素(内部story ),其中href属性以view.php开头。

以下是我的尝试,没有成功:

 let arr = $('#story').find(".el[href.startsWith('view.php')]"); //let arr = $('#story').find(".el[attr('href').startsWith('view.php')]"); console.log(arr); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id='story'> <a class='el' href = 'view.php?id=323'>lorem</a> <a class='el' href = 'about.php'>ipsum</a> <a class='el' href = 'index.php'>lorem</a> <a class='el' href = 'view.php?id=525'>ipsum</a> </div> 

您可以使用a[href^="view.php"]从属性选择器开始,然后使用mapget方法get href值数组。

 let arr = $('#story a[href^="view.php"]').map(function() { return $(this).attr('href') }).get() console.log(arr) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id='story'> <a class='el' href='view.php?id=323'>lorem</a> <a class='el' href='about.php'>ipsum</a> <a class='el' href='index.php'>lorem</a> <a class='el' href='view.php?id=525'>ipsum</a> </div> 

document.querySelectorAll('#story > a[href^="view.php"]')

对于这种情况,这个打印2次你好。

 let arr = []; $('a[href^="view.php"]').each(function() { arr.push(this.getAttribute("href")); }); console.log(arr[0]) console.log(arr[1]) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id='story'> <a class='el' href = 'view.php?id=323'>lorem</a> <a class='el' href = 'about.php'>ipsum</a> <a class='el' href = 'index.php'>lorem</a> <a class='el' href = 'view.php?id=525'>ipsum</a> </div> 

尝试这个:

 const links = document.getElementsByClassName('el') const views = Array.prototype.filter.call( links, el => el.getAttribute('href').startsWith('view') ); console.log(views) 
 <div id='story'> <a class='el' href = 'view.php?id=323'>First view link</a> <a class='el' href = 'about.php'>ipsum</a> <a class='el' href = 'index.php'>lorem</a> <a class='el' href = 'view.php?id=525'>Second view link</a> </div> 

暂无
暂无

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

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