开发者

attr('class') and hasClass() giving conflicting results

I'm getting some confusing results in jQuery, with attr('class') and hasClass(). Basically, I am traversing through table rows and figuring out if the next visible table row has a certain class.

$('table#blocks tr.region').each(function () {
    var next_row = $(this).nextAll('tr:visible');
            
    console.log('This: ' + $(this).attr('class') + ' Next: ' + next_row.attr('class') + ' Next is a region: ' + next_row.hasClass('region'));
                     
 });

When I run this script, the log shows:

This: region region-left Next: region region-right Next is a region: true

This: region region-right Next: region region-content Next is a region: true

This: region region-content Next: draggable even shown_on_home shown_on_infozone Next is a region: true

This: region region-header Next: region-message region-header-message region-empty Next is a region: true

This: region region-footer Next开发者_开发问答: region-message region-footer-message region-empty Next is a region: true

This: region region--1 Next: undefined Next is a region: false

So the message clearly shows that some rows have the class 'region' and some don't, but they all return true for hasClass()!

Can anyone shed some light on this?

Thanks :)


The error comes partially from your use of nextAll() which "Finds all sibling elements after the current element". Thus you always select all visible rows which follow the current one.

The discrepancy between the value returned from attr() and hasClass() can be explained if you reread the documentation about them

attr( name )

Access a property on the first matched element.

vs.

hasClass( class )

Returns true if the specified class is present on at least one of the set of matched elements.

This explains it all. You use nextAll which selects multiple siblings, attr only show the class attribute of the first element matched, while hasClass returns true if one of all the elements matched has the class.

My advice is to use var next_row = $(this).next('tr:visible');. Which will only give you the next visible sibling row.


I've found the answer! When I console.log'd the result of:

var next_row = $(this).nextAll('tr:visible');

it stated that next_row was a [Object object], when it was actually an array of objects. I found this out using debugger;. So i just needed to change the line to:

var next_row = $(this).nextAll('tr:visible:first');

and now it works.

Thanks :)


First of you should never declare "var" in a iterator. Always declare it outside.

Your .hasClass('region') will always return true since your next_row return all tr elements. Use .next('tr:visible') instead.

The reason you get different classes with .attr() is that it returns the first element of your selector.

..fredrik

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜