开发者

jQuery: AddClass

I have a list, where SPANs contains a number. I want to "copy" this number to a STYLE (setting width to the number as percentage) on a SPAN next to it.

HTML

<span class="celebName">Per</span>
<span class="celebPct">32</span>
<span class="celebBar"></span>

jQuery

$('.celebPct').each(function(index) {
    var celebPct = $(this).val();
  开发者_C百科  $(this).next(".celebBar").css({"width": + $(celebPct)+"%";});
});

I want outcome to be like this:

<span class="celebName">Per</span>
<span class="celebPct">32</span>
<span class="celebBar" style="width:32%;"></span>

Why doesn't this work??


Try this:

$('.celebPct').each(function(index) {
    var celebPct = $(this).text();
    $(this).next(".celebBar").css({"width":  celebPct+"%"});
});

Here is a working fiddle: http://jsfiddle.net/maniator/beK89/

Also if you only have one css change you don't need an object in the .css call, you can just do: .css("width", celebPct+"%");


Spans don't have values so try text instead:

var celebPct = $(this).text();


  • use text() not val() to get inner text of a div. val is for inputs
  • no need to wrap the resulting celebPct into a jquery
  • you had a few syntax errors in the hash you passed into css

cleaned up:

$('.celebPct').each(function(index) {
   var celebPct = $(this).text();
   $(this).next(".celebBar").css({"width": celebPct+"%"});
});


This seems to be wrong:

var celebPct = $(this).val();

use

$(this).html()

instead, because span dont have .val only inputs/selects have it.

so this should be the code:

$('.celebPct').each(function(index) {
    var celebPct = $(this).html();
    $(this).next(".celebBar").css({"width": celebPct + "%";});
});

no need to use $(celebPct) as celebPct is not a jquery element


You can't use val() on a span, you'll want to use text(). Also the syntax for your css options is wrong. You can set one option without using an object. Plus the return value from text() is a string value, not jQuery so you needn't wrap it with jQuery when concatenating.

$('.celebPct').each(function(index) {
    var celebPct = $(this).text();
    $(this).next(".celebBar").css( "width", celebPct+"%" );
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜