开发者

Alert class based on it's length with Javascript/jQuery

So basically I'm trying to select the class "on" only, but based on the class length of 2.

<div class="film cars-0317219 on"></div>
<div class="film wall-e-0910970 on"></div>
<div class="film off up-0945232"></div>
<div class="film on finding-nemo-0266543"></div>
<div class="film off cars-0317219"></div>

Something like:

$('div.film').live('click', function(){
var clas开发者_开发知识库ses=$(this).attr("class").split(" ");
var status=classes[classes.length=2];

alert(status);
});

Should alert "on"

Any idea how to get the alert based on the string length? (Likewise, if I put 3 instead of 2 in the code, it should alert "off")


var status=classes[1]; // the second element of the array

Better way to do what you want to do:

var isOn=$('.film').hasClass('on');

alert(isOn?'on':'off');

Remember that $('.film') will only get the 1st element with that class when perform these types of operations unless this is in a handler like click in which case you would use $(this)


You should do:

alert(classes[1]);

arrays in javascript are zero based and so the second element has an index of 1 (and the third element has an index of 2)

EDIT - now i understand the OP means the length of the word on (2 letters):

var classes=$(this).attr("class").split(" ");
for (i = 0; i<classes.length; i++){
   if (classes[i].length ===2){
      alert(classes[i]);
   }
}


If you want to alert only classes of a certain length, you can proceed like this

a=['film', 'cars-0317219', 'on'];//same as your var classes;
var status = a.filter(function(x){
 return x.length==this.size;
},{size:2});//contains ['on']

However filter is implemented for firefox, I don't know for other browsers.


function something(){
var classSplitOn =" ";
var desiredCount = 2;

var onClassSelector = ".on";

$('.film').each(function(index,elem){
  var classString = elem.className;
  if(classString && classString.split(classSplitOn).length == desiredCount){
    var alertVal = "off";
    if($(this).is(onClassSelector)){
      alertVal = "on";
    }
    alert(alertVal);
  }
});
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜