简体   繁体   中英

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('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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM