开发者

Problem reading element attributes with jQuery in IE7

I swear the following code used to work, even in IE7 but now i get

Error: Object doesn't support this property or method

$('div').each(function() {
  if(! this.attr('id').startsWith(开发者_JS百科'light') ) {  
    this.css('zIndex', zIndexNumber);
    zIndexNumber -= 10;
  }
});

Any ideas?

SOLUTION

        $('div').each(function() {

        var divId = new String ( $(this).attr('id') );

        if(! divId.indexOf('light') == 0 ) {  
            $(this).css('zIndex', zIndexNumber);
            zIndexNumber -= 10;
        }

        });


It should be

$(this)

instead of

this

$(this) creates the jQuery object on which you can use all the jQuery functions. this is "only" the DOM element and this element has no e.g. properties attr() or css().

Update:

Are you sure .startsWith() exists? Have you defined it yourself because JS has no such function afaik.

Try:

if($(this).attr('id').indexOf('light') == 0)


I know you've already accepted an answer, but based on your code it looks like you don't need to use an if statement at all if you change your selector:

$('div[id^=light]').each(function() {

        $(this).css('zIndex', zIndexNumber);
        zIndexNumber -= 10;

});

div[id^=light] in your selector means "get all divs whose id begins with 'light'".

Similarly, div[id$=light] will select all divs whose id ends with 'light', and div[id*=light] will select all divs whose id contains 'light' anywhere in it.

This isn't even limited to id. You can use this on any attributes on any element. I know I found this very useful when I first discovered it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜