【问题标题】:Defining generic function jquery定义泛型函数 jquery
【发布时间】:2023-04-03 19:49:01
【问题描述】:

我有一个简单的函数,当用户点击给定的复选框时会显示一个 div。我希望在另一个复选框上具有相同的行为,这就是为什么我想将其概括为传递要显示的元素的函数。

但我不知道 Jquery 上的语法这样做。它会在页面加载时自动触发。有人有想法吗?

代码:

$(document).ready(function() {

$("#transcricao").change( 
    function(){ 
        if ($('.form_transcr').css('display') === 'none') {
            $('.form_transcr').fadeIn(); 
        } else {
            $('.form_transcr').fadeOut();
        }
    }
); //This is working fine!


$("#traducao").change( show_hide($('.form_trad')) ); 
//This is auto-trigerring without user action...

});

这是我的功能:

function show_hide($elm){ 

//This is the "generalized" function that I'd like to use on both
//checkboxes, just passing the element.

if ($($elm).css('display') === 'none') {
        $($elm).fadeIn(); 
    } else {
        $($elm).fadeOut();
    }   
}

【问题讨论】:

  • fadeToggle() 不就是这样做的吗?

标签: javascript jquery function checkbox syntax


【解决方案1】:

它无需用户操作即可自动触发,因为您正在调用它。

使用

$("#traducao").change(function () {
    show_hide($('.form_trad'));
});

当您传递 jQuery 对象时,请直接使用它

function show_hide($elm) {
    //This is the "generalized" function that I'd like to use on both
    //checkboxes, just passing the element.
    if ($elm.css('display') === 'none') {
        $elm.fadeIn();
    } else {
        $elm.fadeOut();
    }
}

【讨论】:

    【解决方案2】:

    .change() 的参数应该是一个函数。您不是在传递函数,而是在调用该函数。

    $("#traducao").change(function() {
        show_hide($('.form_trad'));
    } ); 
    

    顺便说一句,您的show_hide 函数似乎相当于jQuery 的fadeToggle 方法,所以可以是:

    $("#traducao").change(function() {
        $(".form_trad").fadeToggle();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多