This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this questionI wrote a Javascript function that solves a typical problem: Given an HTML element, whenever the user clicks on it another HTML element will be shown, on another click it will be hidden.
As I am not a big Javascript guru and I have just recently started to discover the real power of Javascript, I am sure there is at least a couple of problems with my code.
Any feedback is highly appreciated.
(Note that the I'm using jQuery)
/**
* Makes an HTML element 开发者_如何学Gowith 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>
You could use http://api.jquery.com/toggle/ instead
spelling mistake. toogle is spelt 'toggle'
edit: maybe also make your function name smaller i.e toggle or makeToggle
精彩评论