How to create a “reusable” function in jquery?

≡放荡痞女 提交于 2019-12-05 11:25:15
$.fn.displayVals = function(inputfld, boundfld) {
    this.change(function() {
        var nvenval = $(inputfld).val();
        $(boundfld).val(nvenval);
    }
}

$("select").displayVals();

Check out the jQuery docs on authoring plugins for more info.

Like this if you wanted to make it a jQuery function:

$.fn.displayVals = function() {
// Function stuff goes here
});

$('#element').displayVals()

Inside the function, $(this) works just as you'd expect it to. Just define this outside the docReady and you're all set. Having said that, it looks like you just need to define the selectors in the displayVals() call inside of the .change event:

$("select").change(displayVals('#bphonesel','#bphone'));

Other than that, I'd have to see the rest of your code to understand what might be causing a problem.

I might do something like:

    (function( $ ){
          $.fn.displayVals = function() {

            this.change(function() {
                var val = $(this).val();
                var elemid = $(this).attr("data-elem");
                if (elemid)
                    $("#" + elemid).html(val);
            });

          };
        })( jQuery );

    $(function () {
        $(".display-vals").displayVals();
    });

Then, on any select element that you want this to work on, you can do something like::

<select class="display-vals" data-elem="val-div">
    <option>item 1</option>
    <option>item 2</option>
    <option>item 3</option>
</select>

<div id="val-div"></div>

This uses an html5 style "data-" attribute. This also means that you don't have to set up each individual dropdown in the document load event, each select can specify its own display element in html.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!