问题描述
|
我正在尝试在jquery中创建一些类似于.hide的功能,但是仅使用普通的javascript,这就是我到目前为止所拥有的:
(function() {
addLoadEventHandler(function() {
getByName = (function(name){
return document.getElementsByTagName(name)
})
hide = (function(){
return style.display = \'none\'
})
});
return {
getByName: getByName,hide: hide
};
}());
如此残缺不全,但我是否正沿着正确的方向前进。抱歉,有点菜鸟。
解决方法
隐藏功能需要上下文。您可以像jQuery一样包装DOMElement,或者需要将其传递进来。我将给出两个示例:
var incomplete = (function () {
function hide(DOMElement) {
DOMElement.style.display = \'none\';
}
return {
hide: hide
};
}());
// use like:
incomplete.hide(document.getElementById(\"container\"));
要么
var incomplete = function (context_element) {
function hide() {
context_element.style.display = \'none\';
}
return {
hide: hide
};
};
// use like:
incomplete(document.getElementById(\"container\")).hide(); // like jQuery
, 您需要将其分配给某种
mymodule = function () {
//\"private\" variables:
var privateVar = \"only from within this module.\"
//\"private\" methods:
var getByName = function(name){
return document.getElementsByTagName(name)
}
hide = function(){
return style.display = \'none\'
}
// public interface
return {
getByName: getByName,hide: hide
}
};
}(); // the parens here cause the anonymous function to execute and return