简体   繁体   English

jQuery插件编写:如何在代码中使用选项?

[英]Jquery plugin writing: How do I use the options in my code?

So I'm converting a plugin. 所以我要转换一个插件。 Originally I had a traditional javascript function with some variables I pass in, but I wanted to make it a full Jquery plugin with options. 最初,我具有传递一些变量的传统javascript函数,但我想使其成为带有选项的完整Jquery插件。 The documentation shows you how to set them up, but not how to use them in your code. 该文档显示了如何设置它们,但没有显示如何在代码中使用它们。 Here's a bit of the code: 下面是一些代码:

jQuery.fn.placeholderRX = function(options) {
    var settings = jQuery.extend({
        hoverColor: '#fff',
        addClass: 'null',
        textColor: '#FBFBFB'        
    }, options);

    var $this = $(this);

    $this.children('.inputSpan').each(function() {      
            $(this).children('.inputText').hover( 
                function() {
                    $input.children('.input').css('background-color', hoverColor);
                },
                function() {
                    $input.children('.input').css('background-color', revertColor);
                }
            );
        }       
    });
};

How would I pass that color option value to the hover function beneath it? 如何将颜色选项值传递给它下面的悬停功能? Or more simply, can I just pass the option value to a variable? 或者更简单地说,我可以将选项值传递给变量吗?

You have declared a variable called settings . 您已经声明了一个名为settings的变量。 You can access the hoverColor property of that object with settings.hoverColor : 您可以使用settings.hoverColor访问该对象的hoverColor属性:

$input.children('.input').css('background-color', settings.hoverColor);

The options argument to your plugin will be an object too. 插件的options参数也将是一个对象。 When you pass that in, the extend method will merge the contents of the options object and the "defaults" object, and you assign the result of that merge to settings . 传入时, extend方法将合并options对象和“ defaults”对象的内容,然后将合并结果分配给settings

The following should work: 以下应该工作:

$input.children('.input').css('background-color', settings.hoverColor);

Or what jcreamer898 said works as well: 或jcreamer898所说的同样有效:

$input.children('.input').css('background-color', settings['hoverColor']);

这应该工作...

$input.children('.input').css('background-color', settings['hoverColor'])

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

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