0

I have jQuery read some text then add a class based on the value of this text. (The text read is rendered by my CMS).

The HTML Looks like this:

<ul class="zoneSubscriptions">
 <li>
   <ul>
      <li class="zoneName"><a href="#">Professional</a></li>
      <li>Never</li>
   </ul>
 </li>
 <li>
   <ul>
     <li class="zoneName"><a href="#">RTTM</a></li>
     <li>Never</li>
   </ul>
 </li>
</ul>

I want to read the text of class="zoneName"and add a class based on this.

JS to do this:

$(function() {
   var zone = $( ".zoneName" ).text();
   $( "#zones" ).addClass( zone );
});

This works without issue, however, I need it to add two classes, Professional and RTTM. What it adds is ProfessionalRTTM.

My question is how would I add the classes while keeping a space between the words?

In other words it should render like this: class="Professional RTTM" not class="ProfessionalRTTM"

Note: In my example there are two "zoneName"s. There could be anywhere from 1 to 5 or more when used live.

4

4 回答 4

3

Try iterating the tags:

var $zones = $("#zones");

$(".zoneName").each(function () {
  $zones.addClass( $(this).text() );
});

Also possible (if you want to reuse the list of class names)

var classes = [];
$(".zoneName").each(function () {
  classes.push($(this).text());
});

$("#zones").addClass(classes.join(" "));
于 2013-10-28T21:33:18.927 回答
2

You're calling .text() on multiple results which is joining them together.

Why not do something like this instead:

var zone = $( ".zoneName" ).each(function(){
    $("#zones").addClass($(this).text());
});

Find all your .zoneNames and then call addClass for each one.

jsFiddle example

于 2013-10-28T21:33:27.960 回答
1

You need to iterate across the .zoneNames, otherwise your .text() will be a one undivided string (unless you have whitespace in there)

$(".zoneName").each(function() { 
    $("#zones").addClass($(this).text());
});
于 2013-10-28T21:33:21.203 回答
0

You can use the callback function of addClass(), and use map() to get an array of the text, then simply join with a space:

$('#zones').addClass(function() {
    return $('.zoneName').map(function() {
        return $(this).text();
    }).get().join(' ');
});

Here's a fiddle

于 2013-10-28T21:38:02.267 回答