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 は、メソッド class および 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>