简体   繁体   中英

Javascript simple syntax problem

I have this line of JS which I have determined is wrong.

classes[i] = document.getElementsByAttribute ("class", show_hide_class_selectors[i]);

In context

for (var i = 0; i< show_hide_class_selectors.length; i++) {
        classes[i] = document.getElementsByAttribute ("class", show_hide_class_selectors[i]);
        alert ("ok");
    }

Can someone see where this is wrong?

You invented a non-standard getElementsByAttribute method on the document object, and the code is failing because it doesn't exist.

You should probably looking at using a selector engine; every major JS library includes one, and there are a number of tiny implementations you can use.

for (var i = 0; i< show_hide_class_selectors.length; i++) {
    classes[i] = document.getElementsByClassName (show_hide_class_selectors[i]);
    alert ("ok");
}

if however won't work in IE 6-8. Better use jQuery or another library, providing css selectors for JS

There are numerous implementations for this function on the internet ( example ), but these are cusome implementations that expand the document object.

You can add it in yourself by placing it in your code.

Better still though, if you are wanting to do this sort of thing, then use a JavaScript library such as jQuery this handles all of this for you.

Erm, close, I suppose. You want getElementsByClass .

for (var i = 0; i < show_hide_class_selectors.length; i++) {
  classes[i] = document.getElementsByClass(show_hide_class_selectors[i]);
  alert("ok");
}

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