简体   繁体   中英

jQuery - How to save jQuery block of code in a function

I have a jQuery Code, see below please.

$(document).ready(function () {    
    $('select').on('change', function () {
      var test = this.value;
      console.log(test);
    })

});

which is working perfectly.

Now what I would like to do is, I want to save this code as a function so I can use it somewhere else. Can you help me please?

update

在此处输入图片说明

as you can see on the photo, there is a dropdownlist.

src="https://maps.googleapis.com/maps/api/js?
key=MYAPIKEY&
callback=initAutocomplete

&language=fr" 

what I want to update is, whenever I choose the language from the dropdownlist the src attribute should get updated. In the src attribute you can see the value and in that value the last parameter is language.

I want to update the language parameter according to the dropdownlist.

Create a function like this:

function onChange() {
  var test = this.value;
  console.log(test);
});

Then, use that function as the change event handler:

$(document).ready(function () {    
    $('select').on('change', onChange);
});

Now you can reuse this function for any event handler.

There's multiple answer to store what you've done.

You can just store your action into a function, or you can create and attach the result action function into one function.

 $(".my-select").on("change",function(){ actionAfterChange($(this).val()) }); //Just action function actionAfterChange(value){ console.log("function actionAfterChange > ",value) } //Create event listener and attach a function function attachEventAndAction(element,event,action){ $(element).on(event,function(){ action($(this).val()) }); } attachEventAndAction(".my-select2","change",actionAfterChange)
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="my-select"> <option value="1">1</option> <option value="2">2</option> </select> <select class="my-select2"> <option value="1">1</option> <option value="2">2</option> </select>

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