我在我的应用程序的客户端使用 javascript,我需要根据 id、类和标记名获取元素,我正在使用以下代码获取使用id
.
HTML:
<!Doctype>
<html>
<head>
<script>
(function (tag,fp,n) {
var d = document;
a = d.createElement(tag), m = d.getElementsByTagName(tag)[0];
a.async = 1;
a.src = fp;
m.parentNode.insertBefore(a, m)
})('script', 'cs.js', 'cs');
</script>
</head>
<body>
<div id="id">click me</div>
</body>
</html>
javascript(cs.js):
;(function(w, d) {
var util = {
getElements : function(selector) {
var result = [];
var hashIndex = selector.indexOf("#");
var dotIndex = selector.indexOf(".");
if(hashIndex > -1){
selector = selector.substring(hashIndex+1);
var domElem = d.getElementById(selector);
console.log(domElem);
if(domElem !=null){
result.push(domElem);
}
}
else if(dotIndex > -1){
selector = selector.substring(dotIndex+1);
var domElem = d.getElementsByClassName(selector);
if(domElem !=null){
result = domElem;
}
}else{
var domElem = d.getElementsByTagName(selector);
if(domElem !=null){
result = domElem;
}
}
return result;
}
};
console.log(util.getElements("#id"));
})(window, document);
它在 chrome、firefox 中正常工作,但在 opera 中它给出了null
.
Browser Info:
Opera/9.80 (X11; Linux x86_64) Presto/2.12.388 版本/12.15
这个问题的任何解决方法?