我在为模仿 jQuery 和其他库的练习而创建的小型 Javascript 库时遇到了一些麻烦。截至目前,它不起作用。我对 Javascript 和一般脚本非常陌生,因为我才开始自学,所以我很可能只是错过了对大多数人来说显而易见的东西。我已经尝试过寻找解决方案,但我一直无法找到解决方案,所以我自己求助于它。
这是图书馆本身:
(function(window, undefined) {
var document = window.document
var $m = function(obj) {
if (typeof obj === "object") {
return obj
}
else {
return document.getElementById(obj)
}
class: function(name){
var ele = document.getElementsByTagName('*')
var objects = []
for (var q = 0 ; q < ele.length ; ++q){
if (ele[q].className === name){
objects.push(ele[q])
}
}
return objects
}
s: function(){
return this.style
}
window.$m = $m
})(window)
简要编辑: $m 旨在成为具有方法类和 s 的对象。
这就是它在一个简单的测试页面中的引用方式:
<h1 class="heading" onmouseover="$m(this).s.setAttribute('text-decoration', 'underline')" onmouseout="$m(this).s.setAttribute('text-decoration', 'none')">Testing.</h1>
另一个编辑:我试图这样做,虽然它没有抛出错误,但它不能正常工作。我对到底没有被调用的东西感到有些困惑。
这是新图书馆:
(function(window, undefined) {
//set document to this local scope
var document = window.document
//create $m object
var $m = function(obj) {
//if it is anything but an element return itself
if (typeof obj === "object") {
return new init(obj);
}
//if it is an element return that element
else {
return new init(document.getElementById(obj));
}
}
function init(elem){
//set properties
this.elem = elem;
}
init.prototype = {
//return style
sty: function() {
return this.elem.style;
},
//return all objects with a certain class
cla: function() {
var allelem = document.getElementsByTagName('*')
var give = []
//gather all elements in the document and get those with matching class
for (var q = 0 ; q < allelem.length ; ++q){
if (allelem[q].className === this.elem.className){
give.push(allelem[q]);
}
}
//return found elements
return give;
}
}
//expose $m to global scope
window.$m = $m;
})(window)
并尝试修复它的引用方式:
<h1 class="heading" id="test" onmouseover="$m(this).sty.textDecoration='underline'" onmouseout="$m(this).sty.textDecoration='none'">Testing.</h1>