简体   繁体   中英

How to create a “reusable” function in jquery?

I have this bit of code that works great:

function displayVals() {
    var phonevals = $("#bphonesel").val();
    $('#bphone').val(phonevals);
}

$("select").change(displayVals);
displayVals();

I want to be able to reuse it for all the other select boxes I have on my site. So, I thought I'd use parameters to do it. However, I've so far been unable to get the syntax correct. Here's what I've got, but it doesn't work. Any help would be appreciated.

function displayVals(inputfld, boundfld) {
    var nvenval = $(inputfld).val();
    $(boundfld).val(nvenval);
}

$("select").change(displayVals());
displayVals('#bphonesel', '#bphone');
$.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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