我写了一个解决典型问题的Javascript函数:给定一个HTML元素,每当用户点击它时,将显示另一个HTML元素,在另一个点击它将被隐藏。
由于我不是一个大的Javascript专家,我刚刚开始发现Javascript的真正力量,我相信我的代码至少存在一些问题。
非常感谢任何反馈。
(注意我正在使用jQuery)
/**
* Makes an HTML element with given with ID "targetId" being toggleable
* controlled by the click event of the HTML element with ID "controlId".
* The "controlFunction" is a function that should return true/false based
* on a whether the target should be showed or hidden.
* If there is no controlFunction "!targetElement.is(":visible")" will be used.
* The controlFunction is applied in the context of the control element (so
* the "this" is going to be the controlElement.
*
* @param targetId
* @param controlId
* @param controlFunction
* @returns
*/
var makeToggleableOnClick = function (targetId, controlId, controlFunction) {
var targetElement, controlElement, showHideValue;
if (!targetId || !controlId) {
return;
}
targetElement = $('#' + targetId);
controlElement = $('#' + controlId);
controlElement.css('cursor','pointer');
controlElement.click(function() {
if (controlFunction) {
showHideValue = controlFunction.apply(controlElement,[]);
} else {
showHideValue = !targetElement.is(":visible");
}
if (showHideValue) {
targetElement.slideDown();
} else {
targetElement.slideUp();
}
});
}
/************/
/* EXAMPLE */
/************/
<input id="controlElement" type="checkbox"/>
<div id="targetElement">
Bla-bla.
</div>
<script type="text/javascript">
makeToggleableOnClick('targetElement', 'controlElement', function() {
return this.is(':checked');
});
</script>
答案 0 :(得分:3)
答案 1 :(得分:1)
编辑:也可能使你的函数名更小,即toggle或makeToggle