JQuery从数组中删除特定元素

问题描述 投票:0回答:1

我正在尝试从数组中删除某个元素-具体来说是.top-header .header-info .header-phone a。同时,我正在尝试抓住.top-header .header-info a的其他实例,这是我的代码:

var anchorArray = [];
var titleArray = [];
$('.top-header .header-info a').each(function() {
    var removeItem = $('.top-header .header-info .header-phone a')
    anchorArray.push($(this).attr('href'));
    anchorArray.splice($.inArray(removeItem,anchorArray), 1);
    titleArray.push($(this).html());
    titleArray.splice($.inArray(removeItem,titleArray), 1);
});

<div class="header-info">
  <span class="header-phone"><a href="tel:314-533-1500">314.533.1500</a>&nbsp;or&nbsp;<a href="tel:800-777-2852">1-800-777-ATLAS</a></span>
  <a href="comingsoon">Request a Consultation</a>
  <a href="quickpad">Quick Order</a>
  <a href="contactus">Contact Us</a>
</div>

当前,这似乎正在删除链接的所有实例。

谢谢!

javascript jquery arrays splice
1个回答
0
投票

一种更好的方法是检查元素的父div是否不包含要删除的类。如果没有,则添加该元素。

   <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    </head>
    <body>

    <div class="header-info">
      <span class="header-phone">
      <a href="tel:314-533-1500">314.533.1500</a>&nbsp;or&nbsp;
      <a href="tel:800-777-2852">1-800-777-ATLAS</a></span>
      <a href="comingsoon">Request a Consultation</a>
      <a href="quickpad">Quick Order</a>
      <a href="contactus">Contact Us</a>
    </div>

    <script>
    var anchorArray = [];
    var titleArray = [];
    $('.header-info a').each(function(e,s) {
        if(s.parentNode.className !=="header-phone"){
          console.log(s.parentNode.className);
          anchorArray.push($(this).attr('href'));
          console.log("anchorArray:"+anchorArray);
          titleArray.push($(this).html());
        }
    });

    console.log(titleArray);
    </script>
    </body>
    </html> 
© www.soinside.com 2019 - 2024. All rights reserved.