开发者

Using JQuery how do you create a control the name of a class?

I'm using append in the following way:

$('#city').append('<div class="c">' + value['name'] + '. ' + value['city'] + ', ' + 
                        value['state'] +' ' +  value['zip'] + ' ' + '</div>');

Which results in something like this:

<div class="c">
Antone Stark. Doyletown, Rhode Island 43467 
</div>

How do you use value['state'] to name the class?

<div c开发者_开发百科lass="MyCustomClass">


If the states were two letter codes, you could do this:

$('#city').append('<div class="'+value['state']+'">' + value['name'] + '. ' + value['city'] + ', ' + 
                    value['state'] +' ' +  value['zip'] + ' ' + '</div>');

However, classes are space-separated meaning they are treated as separate when split up by spaces. So if you add something there with a space (like "Rhode Island"), it will treat them as separate classes (e.g., "Rhode" and "Island") so you may wish to replace spaces with an underscore or the like.

$('#city').append('<div class="'+value['state'].replace(/ /g, '_')+'">' + value['name'] + '. ' + value['city'] + ', ' + 
                    value['state'] +' ' +  value['zip'] + ' ' + '</div>');

So in the case of Rhode Island, that will produce:

<div class="Rhode_Island">

which you can then reference in CSS:

.Rhode_Island {color:blue}

or jQuery:

$('.Rhode_Island').... (do something)

etc.

However, if you are not repeating these, it might be more appropriate to generate it as an id rather than a class (i.e., to produce <div id="Rhode_Island"> instead of <div class="Rhode_Island">).


$('#city').append('<div class="' + value['state'].replace(/ /g, '_') + '">' ...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜