Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery attr does not seem to return string?

I have the following code :

JS:

var test2 = ['RMrpi5Z8doc','JIPbUaqyYx0','MbjXYg0YRmw'];

    $('tr').live('click', function(event){
      $($(this).attr('class').split(' ')).each(function() { 
        if (!((this == 'even') || (this == 'odd'))) {
            alert(jQuery.inArray(this, test2));
            if (this == 'RMrpi5Z8doc') {
              alert(this);
            }
        }   
      });
    });

HTML :

  <table>
   <tr class="odd RMrpi5Z8doc">
     <td>Kite</td>
     <td>Just Like Vinyl</td>
     <td>Audiotree</td>
   </tr>
  </table>

inArray does not match and returns -1. The if statement matching the literal string does match. If I substitute in the literal in inArray, that also matches.

I've seen a post which said that jQuery attr does not return strings anymore, but looking at the documentation for attr on the jQuery site seems to say it does.

Perhaps I should be going about this an entirely different way?

like image 917
William Avatar asked Oct 22 '12 13:10

William


2 Answers

You're using the wrong each. You meant jQuery.each, the general-purpose iterator:

$.each($(this).attr('class').split(' '), function ...);

not each, the instance function on jQuery instances:

$($(this).attr('class').split(' ')).each(function ...); // Wrong

In particular, what's happening is this part of the above:

$($(this).attr('class').split(' '))

...calls $() with the array, which doesn't do what you want it to do. :-)

like image 127
T.J. Crowder Avatar answered Nov 09 '22 09:11

T.J. Crowder


I've refactored this using :

$(document).on('click', 'tr', function(){
  alert(jQuery.inArray($(this).attr('id'), test2));
}

Which seems to work. I have moved the class name to an id field since I'm not using these identifiers for any stylesheets, they really are ids.

like image 25
William Avatar answered Nov 09 '22 07:11

William