简体   繁体   中英

how to add attribute to each list item

i have a string which looks like this:

.a,.b,.c,.d

i would like to add a value to an attribute of every one of these items.

i used this before to add a value to items where i change the height:

$(this).attr("heightwert", parseInt($(this).css('height')));

i use this attribute for sorting. but if you know how i could sort by the dynamical height of elements this would be great too.

this i use for sorting:

onclick="$('ul.dataa>li').tsort('a',{attr:'heightwert',order:'desc'});"

This was written with the assumption that the .a,.b,.c,.d was a reference to the class-names of elements on the page, though reading the comments that follow my posting this answer I'm not sure that this is, indeed, the case. However, on my original assumption, the following seems to do what (I thought) you asked:

$('.a, .b, .c, .d').attr('data-heightwert', function(i, val) {
    return $(this).height();
});

JS Fiddle demo .

Please note that I'm using the attribute data-heightwert rather than simply heightwert as that would be an invalid attribute of an html element, whereas the data- prefix allows for elements to be assigned/created as necessary by the developer and retain validity of the code. Admittedly this is under html 5, but it's backwards compatible with html 4.x, and is, at worst, no less valid than simply using heightwert in such doctypes.

The heights of the elements that appear on :hover in this demo are reported by the CSS and taken from the data-heightwert element as set by jQuery.

References:

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