简体   繁体   中英

Looping through same JavaScript function on multiple (html)elements property change

Is there a way to looping JavaScript function for multiple fields?

For eg I have 5 textboxes such as:

text1
text2
text3
text4
text5

Now, Each of them does the same thing on "focusout" and hence I dont want to write five different JS functions for each of them:

$('#text1').focusout( {
.............
    });

$('#text2').focusout( {
.............
    });

$('#text3').focusout( {
.............
    });

$('#text4').focusout( {
.............
    });

$('#text5').focusout( {
.............
    });

How can I avoid writing five different functions here?

Thanks in advance

Use a common class:

<input type="text" class="focusClass" />
<input type="text" class="focusClass" />

and this JS:

$('.focusClass').focusout(function() {
    // ...
});

Other option is to join them together, but this way is harder to maintain:

$('#text1, #text2, #text3, #text4, #text5 ').focusout(function() {
    // ...
});

在选择器中,选择要使用的所有元素:

$('#text1, #text2, #text3, #text4, #text5')

If it doesn't makes sense to put the same class on all the elements, you may combine the selectors with a comma:

$('#text1, #text2, etc...., #text5').focusout( {
.............
});

Alternately, you could declare the function and then pass it as a parameter to each of your selectors through the focusout call:

var onFocusOut = function() {
 do something
};

$('#text1').focusout(onFocusOut);
$('#text2').focusout(onFocusOut);
$('#text3').focusout(onFocusOut);
$('#text4').focusout(onFocusOut);
$('#text5').focusout(onFocusOut);

Well this is a short way to do it...

$("#text" + [1,2,3,4,5].join(", #text")).focusout(function () {...});

But I'm wondering if you can't add a class to the elements so you can select them at once.

For example...

<input type='text' id="text1' class='textfield' />
<input type='text' id="text2' class='textfield' />
<input type='text' id="text3' class='textfield' />

Then use the following selector...

$(".textfield").focusout(function () {...});

Other option is that you have a parent container with an id which gives you the following option...

<div id="formfields">
    <input type='text' id="text1' class='textfield' />
    <input type='text' id="text2' class='textfield' />
    <input type='text' id="text3' class='textfield' />
</div>

The selector then looks like this...

$("#formfields input[type=text]").focusout(function () {...});

Update Added two more options to select your fields

You can pass the IDs of the text box to the jQuery functions to carry out your task..

try this:

function myFunction(IDofObject)
{
    $( "#"  + IDofObject  ).doSomething();
}

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