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

时间:2019-02-08 10:17:59

标签: javascript jquery

我需要具有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>

4 个答案:

答案 0 :(得分:6)

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

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>

答案 1 :(得分:3)

private Bitmap rescaleBitmap(Bitmap bitmap) { float constant = 600.0f / bitmap.getWidth(); return Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * constant), (int) (bitmap.getHeight() * constant), true); }

答案 2 :(得分:1)

在这种情况下,此命令会打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>

答案 3 :(得分:0)

尝试一下:

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>