开发者

can we use a .each within a .each in jquery?

开发者 https://www.devze.com 2023-03-06 07:43 出处:网络
$(\"[name=form_1]\").each(function(){ alert(\"i in else\"+i); $(\'.eform_text\').each(function() { }); });
$("[name=form_1]").each(function(){
    alert("i in else"+i);
    $('.eform_text').each(function() {
    });
});

would this loop iterate over all elements that have a class of eform_text only in form1 .Or would it iterate over all elements which have that class ?

Update:

The exact jsp code is as follows:

<c:when test="${eformDetails.controlType==1}"> <input i开发者_Go百科d="textBox_${eformDetails.id}_${eformDetails.required}_${i}" class="eformDetail eform_text" type="text" value="" name="form_${i}" onblur="validateEformInputs(${i-1})"></input> </c:when>

i have the form which varies each time.and for each form i need to obtain all the text boxes.Currently after your help my javascript is ass follows:

$("[name=form_"+i+"]").each(function(i){ alert("i in else"+i);

         $('.eform_text', this).each(function() {
        textboxId = $(this).attr("id");

It reaches the first alert but i am not able to reach the second loop.It is not obtaining elements that have class eform_text.Not sure what is going wrong here.Could you please help?


It would iterate over all elements with that class, whether inside a form with the name "form_1" or not. To only look within each form (I'm guessing you must have more than one form with the name "form_1", though that seems odd), use find in the outer loop in order to scope the inner loop:

$("[name=form_1]").each(function(formIndex) {
    alert("formIndex in each: " + formIndex);
    $(this).find('.eform_text').each(function(textIndex) {
        alert("textIndex in each: " + textIndex);
    });
});

Or you can use the second argument to $(), which provides the context in which to work:

$("[name=form_1]").each(function(formIndex) {
    alert("formIndex in each: " + formIndex);
    $('.eform_text', this).each(function(textIndex) {
        alert("textIndex in each: " + textIndex);
    });
});

Either should work.

Note that as @Shrikant Sharat pointed out in the comments (thanks Shrikant!), I've assumed the i in your original code is meant to be the index that gets passed into each. I've shown the indexes at both levels (with descriptive names) above.


Your second answer.

Because you're calling $( each time, it instantiates a new copy of the jQuery object which doesn't care what level of a function it's in.

It would loop through every element with that class.


$('.element').each(function(){

    $(this).find('.elementChild').each(function(){

        // do something

    });

});
0

精彩评论

暂无评论...
验证码 换一张
取 消