jquery 如何从链接中获取href值以用作value?

efzxgjgh  于 2023-01-12  发布在  jQuery
关注(0)|答案(2)|浏览(148)

我有以下设置:

<div class="map-container">
  <div class="map-pointer">
    <a href="https://my-link-1.com"></a>
  </div>
  <div class="map-pointer">
    <a href="https://my-link-2.com"></a>
  </div>
  <div class="map-pointer">
    <a href="https://my-link-3.com"></a>
  </div>
  ... 15 .map-pointer div's in total
</div>

我想做的是,a元素的内容将自动填充为从https://、'-'和. com中剥离出来的href.的值。
所以我的链接最终看起来像这样:

<a href="https://my-link-1.com">my link 1</a>
<a href="https://my-link-2.com">my link 2</a>
...

这在jQuery中可行吗?我不知道从哪里开始。我知道我首先必须将href属性存储在变量中。但是我如何对所有不同的链接做到这一点呢?

jv4diomz

jv4diomz1#

可以做这样的事情:

$("a").each(function() {
     var linkName;
     linkName = this.href.replace("https://", "");
     linkName = linkName.replace(/-/g," ");
     linkName = linkName.replace(".com/", "");
     this.innerHTML = linkName;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="map-container">
  <div class="map-pointer">
    <a href="https://my-link-1.com"></a>
  </div>
  <div class="map-pointer">
    <a href="https://my-link-2.com"></a>
  </div>
  <div class="map-pointer">
    <a href="https://my-link-3.com"></a>
  </div>
</div>
m1m5dgzv

m1m5dgzv2#

你可以试试这个:

let title = '';
$('.map-container a').map( function() {
    let href = $(this).attr('href');
    title = href.replace('https://', '').replace('.com', '').replaceAll('-', ' ');
    console.log(title)
    $(this).html(title);

}).get();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="map-container">
  <div class="map-pointer">
    <a href="https://my-link-1.com"></a>
  </div>
  <div class="map-pointer">
    <a href="https://my-link-2.com"></a>
  </div>
  <div class="map-pointer">
    <a href="https://my-link-3.com"></a>
  </div>
</div>

相关问题