简体   繁体   English

JQuery 从数组中删除特定元素

[英]JQuery Remove Specific Element From Array

I'm trying to remove a certain element from my array - specifically, .top-header .header-info .header-phone a .我正在尝试从我的数组中删除某个元素 - 特别是.top-header .header-info .header-phone a At the same time, I'm trying to grab each other instance of .top-header .header-info a Here's my code:同时,我试图互相抓取.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>

Currently, this seems to be removing all instances of a links.目前,这似乎正在删除链接的所有实例。

Thanks!谢谢!

A better way for you to do this is to check if the parent div of the element doesnot contain the class you wish to remove.执行此操作的更好方法是检查元素的父 div 是否不包含要删除的类。 If it doesnt, then add that element.如果没有,则添加该元素。

   <!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> 

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

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