开发者

how to add attribute to each list item

开发者 https://www.devze.com 2023-03-18 21:39 出处:网络
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

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:

开发者_StackOverflow社区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:

  • attr().
  • height().
  • data- custom arbitrary data-storage attributes.
0

精彩评论

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