我有这个HTML:

<div class="info">
    <div class="form-group">
        <label class="control-label col-sm-2">Title</label>
            <div class="col-xs-10 col-sm-8">
                <input id="titleInfo" class="form-control" type="text" placeholder="Title">
            </div>
        <div class="col-xs-1 col-sm-1">
            <button class="btn btn-default remove_field"><i class="fa fa-remove"></i></button>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2">Text</label>
        <div class="col-xs-10 col-sm-8">
            <textarea id="textInfo" class="form-control" type="text" placeholder="..."></textarea>
        </div>
    </div>
</div>

在我的jsp中,我有很多这样的东西:
<div class="info">
    ...
</div>
<div class="info">
    ...
</div>
<div class="info">
    ...
</div>

现在,我将以类信息的升序更改id标签:每个div的titleInfo和textInfo。
<div class="info">
    ..<input id="titleInfo1"..
    ..<textarea id="textInfo1"..
</div>
<div class="info">
    ..<input id="titleInfo2"..
    ..<textarea id="textInfo2"..
</div>
<div class="info">
    ..<input id="titleInfo3"..
    ..<textarea id="textInfo3"..
</div>

等等。

我想按类(class)信息进行迭代:
var x = 1;
$(".info").each(function() {
    //Now, I don't know how to change the ids
    x++;
});

最佳答案

您需要将代码更新为以下内容

var x = 1;
$(".info").each(function() {
    var elems = $(this).find(".form-control"); // get all the input elements with class form-control
    elems.each(function() { // iterate over the elements
         $(this).attr("id", $(this).attr("id") + x); // update id
    });
    x++;
});

更新
var x = 1;
    $(".info").each(function() {
        var elems = $(this).find(".form-control"); // get all the input elements with class form-control
        $(elems[0]).attr("id", "titleInfo" + x);
        $(elems[1]).attr("id", "textInfo" + x);
        x++;
    });

关于javascript - 如何更改按类迭代的id值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31345350/

10-09 13:06