How to create a “reusable” function in jquery?

不问归期 提交于 2019-12-10 06:36:22

问题


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');

回答1:


$.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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/8251164/how-to-create-a-reusable-function-in-jquery

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