开发者

How do I get the class of each ul>li item as a serial string?

开发者 https://www.devze.com 2023-02-19 02:22 出处:网络
I\'m trying to the get the class of each item in an unordered list, and turn it into a serialised string that can be sent back as an AJAX call.

I'm trying to the get the class of each item in an unordered list, and turn it into a serialised string that can be sent back as an AJAX call.

After a day's messing around with jQuery (that I like but am not very familiar with - seems so much harder than server-side stuff) am still no further. Can anyone provide some pointers?

So something like

<ul>
    <li class="expanded">Some text</li>
    <li class="expanded">Some text</li>
    <li>Some text</li>
    <li>Some text</li>
    <li class="expanded">Some text</li>
</ul>

would result in a string like

1,1,0,0,1

which is easily storable and parsable.


What I'm ultimately trying to do is to create an expandable list with the following characteristics:

  • Clicking on an entry unhides a div
  • Multiple items can be open at once, i.e. not an accordian system
  • Maintains state, preferably via an Ajax call when a change is made, but client-side cookie is acceptable (e.g. would send a string like '0,1,1,0,0' meaning items 2&3 are open).

I've been using the excellent example #3 at

开发者_开发技巧http://www.i-marco.nl/weblog/jquery-accordion-3/ as documented at

http://www.i-marco.nl/weblog/archive/2010/02/27/yup_yet_another_jquery_accordi

The author says "you can control the state of your accordions by having your page generation code set this class" but sadly provides no pointers how to get the state out.

Can anyone suggest a postential strategy of how to do this?

I've tried to loop through each item to get the class, with a view to serialising the list of item indexes - I thought something like

var target = $('ul.menu > li.active');
$.each(target, function(index, attributes) {
    alert(attributes.attr('class'));
});

might be a start, but hours trying different things aren't even getting me that far - just listing the current state.


You mean something like this?

var status = $('ul > li').map(function() {
     return +$(this).hasClass('expanded');
}).get().join(',');

This will create an array of 0s and 1s and joins it with , to create a string.

Note: I use an unary + to convert true and false to their numerical representations 1 and 0.

Reference: jQuery.fn.map, jQuery.fn.hasClass, jQuery.fn.get, Array.prototype.join

0

精彩评论

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