javascript 带参数的jquery函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4373089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 11:12:05  来源:igfitidea点击:

jquery function with parameters

javascriptjquery

提问by Linda725

i have several checkboxes that when checked show a hidden div. Is there a way to write a jquery function that will show or hide based on whether the checkbox is checked the hidded div?

我有几个复选框,选中时显示隐藏的 div。有没有办法编写一个 jquery 函数,该函数将根据复选框是否被选中隐藏 div 来显示或隐藏?

using just javascript

只使用 javascript

<input type="checkbox" name="box1" id="box1" onclick="function toggle('div1')">
<div id='div1'>
.....
</div>

<input type="checkbox" name="box2" id="box2" onclick="function toggle('div2')">
<div id='div2'>
.....
</div>


<script>
function toggle(id) {
if (this.checked) show(id);
else hide(id);
}

where show()and hide()are functions define to change the display attribue of the id.

whereshow()hide()are 函数定义更改 id 的显示属性。

Is there some way to do this in jquery where I bind the toggle to the checkbox adn have it toggle an id that is passed somehow?

有什么方法可以在 jquery 中做到这一点,我将切换开关绑定到复选框并让它切换以某种方式传递的 id?

回答by Jacob Relkin

You can try creating a small jQuery plugin:

您可以尝试创建一个小型 jQuery 插件:

$.fn.toggleCheckboxContainer = function(selector) {
   var toggleObject = $(selector);
   return $(this).each(function() {
      $(this).change(function() {
        $(this).is(':checked') ? toggleObject.show() : toggleObject.hide();
      });
   });
};

$(function() {
    $('#box1').toggleCheckboxContainer('#div1');
    $('#box2').toggleCheckboxContainer('#div2');
});

jsFiddle example

jsFiddle 示例