javascript - 使用新的 div 字段增加 div id 编号

以下脚本创建最多 4 个的新输入字段。我需要知道如何增加 ID,如下所示。

第一次点击,“var fieldHTML”生成:

<div><input type="text" id="sPhone_1" value=""/><a href="javascript:void(0);" class="remove_button"><img src="remove-icon.png"/></a></div>

第二次点击:id="sPhone_2" 第三次点击:id="sPhone_3" 以此类推..

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){
    var maxField = 4; //Input fields increment limitation
    var addButton = $('.add_button'); //Add button selector
    var wrapper = $('.field_wrapper'); //Input field wrapper
    var fieldHTML = '<div><input type="text" id="sPhone_" value=""/><a href="javascript:void(0);" class="remove_button"><img src="remove-icon.png"/></a></div>'; //New input field html 
    var x = 1; //Initial field counter is 1

    //Once add button is clicked
    $(addButton).click(function(){
        //Check maximum number of input fields
        if(x < maxField){ 
            x++; //Increment field counter
            $(wrapper).append(fieldHTML); //Add field html
        }
    });

    //Once remove button is clicked
    $(wrapper).on('click', '.remove_button', function(e){
        e.preventDefault();
        $(this).parent('div').remove(); //Remove field html
        x--; //Decrement field counter
    });
});
</script>

<div class="field_wrapper">
    <div>
        <input type="text" name="Phone" id="sPhone" value=""/>
        <a href="javascript:void(0);" class="add_button" title="Add field"><img src="add-icon.png"/></a>
    </div>
</div>

回答1

$(addButton).click(function(){
        //Check maximum number of input fields
        if(x < maxField){ 
            x++; //Increment field counter
            $(wrapper).append(fieldHTML); //Add field html
            newId = 'sPhone_' + x;
            document.getElementById('sPhone_').id = newId;
        }
    });

尝试这个。这应该在 html 中使用初始 id sPhone_ 发布 div,然后它会获取该元素并将 id 替换为您新创建的 id。

或者您可以创建字符串以附加到函数中,如下所示:

$(addButton).click(function(){
        //Check maximum number of input fields
        if(x < maxField){ 
            x++; //Increment field counter
            var fieldHTML = '<div><input type="text" id="sPhone_"' + x + 'value=""/><a href="javascript:void(0);" class="remove_button"><img src="remove-icon.png"/></a></div>'; //New input field html 
            $(wrapper).append(fieldHTML); //Add field html
        }
    });

相似文章

html - CSS 紧凑水平树

我有一个包含嵌套列表(<ul>+<li>)的HTML。我想使用CSS将其显示为紧凑的水平树。https://codepen.io/Hojy/pen/OzXbvp几乎完全符合我的要求,但我想让树更紧凑—...

随机推荐

最新文章