简体   繁体   中英

Removing item from array without iterating

I've looked through some documentation, but I feel like there's an easier method to remove one item from an array without using an iteration loop.

http://jsfiddle.net/G97bt/1/

Updated jsFiddle: http://jsfiddle.net/G97bt/6/ using not()


<button id="1">1</button>
<button id="2">2</button>
<button id="3">3</button>

<div id="1a">Test</div>
<div id="2a">Test</div>
<div id="3a">Test</div>

var $myList = $("#1a, #2a, #3a");

$("#1").on("click", function() {
    $myList.fadeOut(); // I want to fade DIVs #2a + #3a, not ALL
    $("#1a").fadeIn("slow");    
});
$("#2").on("click", function() {
    $myList.fadeOut(); // I want to fade DIVs #1a + #3a, not ALL
    $("#2a").fadeIn("slow");    
});
$("#3").on("click", function() {
    $myList.fadeOut(); // I want to fade DIVs #1a + #2a, not ALL    
    $("#3a").fadeIn("slow");    
});

This is how I'm envisioning it would function:

$myList.remove['#1a'].fadeOut();

Like below, by using .not to remove elements from the set of matched elements:

$myList.not('#1a').fadeOut();

And note $myList is not an array but a jQuery object(even it behaves like an array).

You could also rewrite your code like below:

var $myList = $("#1a, #2a, #3a");

$("#1,#2,#3").on("click", function() {
    $myList.not('#'+this.id+'a').fadeOut();
    $('#'+this.id+'a').fadeIn("slow");    
});

The working demo.

You can use like this

$("button").click(function(){
  $("[id$=a]").hide();

  $("#"+this.id+"a").show();
});

采用

$arrayName.splice(position, number of elements)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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