简体   繁体   English

可更改属性作为jQuery插件中的参数

[英]changeable attribute as a parameter in jQuery plugin

I'm writing a plugin where I would need to "Bind" a parameter. 我正在编写一个需要“绑定”参数的插件。 Sometimes I need the value of this.checked, but sometimes it's $(this).val() what I need, and there are cornercases when I need to check other attributes. 有时我需要this.checked的值,但有时我需要的是$(this).val(),并且在需要检查其他属性时会遇到一些麻烦。

I need an "input parameter" for the initialization which somehow determines what to check for the value. 我需要一个“输入参数”进行初始化,该初始化以某种方式确定要检查的值。

I can do this with eval, but it's evil. 我可以用eval做到这一点,但这是邪恶的。 I can do this with a switch case, but I'm not sure I can prepare for everything. 我可以使用开关盒来完成此操作,但是我不确定我可以为所有事情做准备。

What is the best way to do this? 做这个的最好方式是什么?

$.fn.formSwitch = function (options) {

    var settings = $.extend({
        visibleholder: '#visible_holder',
        hiddenholder: '#hidden_holder',
        reparseform: this.closest('form')
    }, options);



    this.change(function () {
        switchFormPart(settings.visibleholder, 
            settings.hiddenholder, 
            ********this.checked, *********** <- I would like this as a parameter
            settings.reparseform
        );
    });
};

You can pass a string like "checked" or "val" as parameter and then: 您可以将"checked""val"类的字符串作为参数传递,然后:

this.change(function () {
    switchFormPart(settings.visibleholder, 
        settings.hiddenholder, 
        param in this ? this[param] : $(this)[param](),
        settings.reparseform
    );
});

If param is "checked" , it will do equivalent to this.checked 如果param被"checked" ,它将等效于this.checked

If param is "val" , it will do equivalent to $(this).val() 如果param是"val" ,它将等同于$(this).val()

And so on. 等等。

Look into bracket notation , conditional operator and in operator 查看括号符号条件运算符in运算符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM