开发者

How to Add/Remove value from a list?

开发者 https://www.devze.com 2023-03-23 01:46 出处:网络
I need to add and remove items from a list of integers.There will be no repeats in the list. I will pass the list to a query and display the results.Right now, I just need to be able to start with an

I need to add and remove items from a list of integers. There will be no repeats in the list. I will pass the list to a query and display the results. Right now, I just need to be able to start with an empty list and as the user selects items, the list will be populated.

The idea is that when a user clicks on the first time, the item will be bolded and its ID will be added to the list. The second time an item is clicked on, the item will be unbolded and the ID will be removed from the list. Easy, right?

<script type="text/javascript">
$(document).ready(function() {

    MyList = "";

$(".Cat").live("click", function() {
    CurrentClass = $(this).attr("class");
    // CLICKED
        if (CurrentClass == "Cat") {
        $(this).addClass("Bold");
            NewItem = $(this).attr("id");
            // ADD ITEM TO LIST
            MyList = 
        // UNCLICKED 
        } else {
        $(this).removeClass("Bold");
            NewItem = $(this).attr("id");
            // REMOVE ITEM FROM LIST
            MyList =   
    }
});

});
</script>

<span id="1" class="Cat">1</span>

<span id="2" class="Cat">2</span>

<开发者_Python百科span id="3" class="Cat">3</span>


initialize list:

var myList = []

add:

myList.push(NewItem)

remove:

myList.splice( $.inArray(NewItem, myList), 1 );

I think that was the main question, bolding/unbolding the item is usually done through adding/removing a class. And I see you've already done that.


Definitely sounds like you want an array. But here's an example that keeps MyList simply as a string:

http://jsfiddle.net/bf8wE/1/


I'd us an array and keep it simple:

$(document).ready(function() {

    var MyList = new Array();

$(".Cat").live("click", function() {
    CurrentClass = $(this).attr("class");
    // CLICKED
        if (CurrentClass == "Cat") {
        $(this).addClass("Bold");
            NewItem = $(this).attr("id");
            // ADD ITEM TO LIST
            MyList.push(NewItem); 
        // UNCLICKED 
        } else {
        $(this).removeClass("Bold");
            NewItem = $(this).attr("id");
            // REMOVE ITEM FROM LIST
            MyList.splice( $.inArray(NewItem, MyList), 1 );  
    }
});

});

Once you have this array populated, displaying it as an actual comma-separated list is as simple as MyList.join(',')

0

精彩评论

暂无评论...
验证码 换一张
取 消