简体   繁体   中英

How to pass parameter in javascript function

I want to pass one parameter to a function called ForPaste() .

My function is given below:

 var regex = /^[A-Za-z0-9ĀĒĪŌŪāēīōū\.\-\~\`\'' ]*$/;
    var SalaryRegex = /^[A-Za-z0-9\,\.\/\$ ]*$/;
        $.fn.ForPaste = function () {
            return this.each(function () {
                $(this).bind('input propertychange', function () {
                    var value = $(this).val();
                    if (!regex.test(value)) {
                        $(this).val("");
                    }
                });
            });
        };

This function is in a common JS file. It is called on individual pages. I want to test the regex depending on the parameter passed. So can I know the method about to call the ForPaste() function with the parameter.eg $("#Text1").Forpaste('FromForm1'); and I get this FromForm1 in the ForPaste() function.

You define a formal parameter for your function.

      // formal parameter--v
$.fn.ForPaste = function (the_value) {

    alert( the_value ); // displays the argument passed

    // rest of your code
};

Whatever value was passed to ForPaste() will be referenced by the_value . (Of course you can change the name to any valid identifier.)

not sure what you are trying to do, because the answer seems so obvious. Will this do?

$.fn.ForPaste = function (theName) {
    if (theName.test(//)){
        return this.each(function () {
            ....
        });
    }
    return false
};

you can access the parameters by looking at arguments which isn't an array, but seems to be one. from within the function you can do an var theName=arguments[0] to get the value of the first parameter

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