开发者

Add CSS Class to link based on Character Count with jquery

I have links that load dynamically onto a background to make them look like buttons. Some of the links take up two lines and some of the links take up 1 line. Eithe way they need to be vertically centered.

My plan to to append a class based on the number of开发者_JAVA百科 characters and then adjust the padding from there.

So if the link's text is 25 characters (including spaces) or less - append class 'small'

if the link's text is greater than 25 characters - append class 'large'

How would I go about doing this with jQuery?


You could do this:

$(function() {
  $("#backgroundID a").each(function() {
    $(this).addClass($(this).text().length > 25 ? "large" : "small");
  });
});

If you wanted all links, just change the selector to $("a"). You mentioned dynamic loading but not exactly what dynamic meant...if you're loading via ajax, for example $.ajax(), you could do this:

$.ajax({
  //options...
  success: function(data) {
    //do stuff with links
    $("a", data).each(function() {
      $(this).addClass($(this).text().length > 25 ? "large" : "small");
    });
  }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜