添加更多输入的唯一名称

我正在尝试创建一个添加更多按钮,它将创建一个新的输入字段。但是,我想为它设置一个唯一的名称。

所以,基本上我试图使我的 namefield 唯一的是使用 php 方法rand()。这个概念是 - 当点击添加更多按钮时,它将有一个名称附加到由rand().


然而,发生的情况是它获取由 生成的值rand()并将其应用于所有生成的输入的所有名称。


这是我的代码和我尝试过的:


HTML:


<div class="field_wrapper">

    <div>

        <input type="text" name="field_name[<?php echo rand(); ?>]" value=""/>

        <a href="javascript:void(0);" class="add_button" title="Add field">Add More</a>

    </div>

</div>

JQUERY / JAVASCRIPT:


<script type="text/javascript">

$(document).ready(function(){

    var maxField = 100; //Input fields increment limitation

    var addButton = $('.add_button'); //Add button selector

    var wrapper = $('.field_wrapper'); //Input field wrapper

    var fieldHTML = '<div><input type="text" name="field_name[<?php echo rand(); ?>]" value=""/><a href="javascript:void(0);" class="remove_button">Remove</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>

如您所见,第一个字段按预期生成数字。如果您单击添加更多,则第二个字段会创建一个唯一编号。但是,如果您再次单击添加更多,第三个字段将复制与第二个字段相同的名称。


我如何去实现我想要的,为什么rand()不生成新代码?


另外,是否可以rand()保证它是唯一的 ID 还是它有机会重复相同的数字?


如果它确实重复,那么使它尽可能独特的最佳方法是什么?


森栏
浏览 154回答 3
3回答

小怪兽爱吃肉

如果您使用 PHP 生成随机名称,则会在服务器上完成一次。然后您的 JS 代码复制相同的元素。你需要的是用js生成唯一的名字。如果可以,请避免随机,理论上,您可以命中相同的数字并遇到神秘的错误。var generateField = function(name){&nbsp; &nbsp; &nbsp;return '<div><input type="text" name="'+name+'" value=""/><a href="javascript:void(0);" class="remove_button">Remove</a></div>'; //New input field html&nbsp;}//Once add button is clicked$(addButton).click(function(){&nbsp; &nbsp; //Check maximum number of input fields&nbsp; &nbsp; if(x < maxField){&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; x++; //Increment field counter&nbsp; &nbsp; &nbsp; &nbsp; $(wrapper).append(generateField('field_name['+x+']' ) ); //Add field html&nbsp; &nbsp; }});

胡说叔叔

随机并不一定意味着唯一,即使碰撞极其罕见。这个解决方案只是增加一个totalFieldsCreated变量来获得下一个唯一数字(直到 JavaScript 可以提供的最大值。)新字段是动态创建的,而不是使用固定的 HTML 字符串。(这种技术更灵活。)$(document).ready(function() {&nbsp; // Defines global identifiers&nbsp; let&nbsp; &nbsp; currentFieldCount = 1,&nbsp; &nbsp; totalFieldsCreated = 1;&nbsp; const&nbsp; &nbsp; maxFieldCount = 100,&nbsp; &nbsp; addButton = $('.add_button'),&nbsp; &nbsp; wrapper = $('.field_wrapper');&nbsp; // Calls `addField` when addButton is clicked&nbsp; $(addButton).click(addField);&nbsp; // Executes anonymous function when `Remove` is clicked, which removes&nbsp; //&nbsp; &nbsp;the parent div, and decrements (and logs) `currentFieldCount`&nbsp; $(wrapper).on('click', '.remove_button', function(e) {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; $(this).parent('div').remove();&nbsp; &nbsp; currentFieldCount--;&nbsp; &nbsp; console.log(`currentFieldCount: ${currentFieldCount}`);&nbsp; });&nbsp; // Defines the `addField` function&nbsp; function addField(){&nbsp; &nbsp; // Makes sure that `currentFieldCount` and `totalFieldsCreated`&nbsp;&nbsp; &nbsp; //&nbsp; &nbsp;are not at maximum before proceeding&nbsp; &nbsp; if(&nbsp; &nbsp; &nbsp; currentFieldCount < maxFieldCount &&&nbsp;&nbsp; &nbsp; &nbsp; totalFieldsCreated < Number.MAX_VALUE&nbsp; &nbsp; ){&nbsp; &nbsp; &nbsp; // Creates an input element, increments `totalFieldsCreated`,&nbsp; &nbsp; &nbsp; //&nbsp; &nbsp;and uses the incremented value in the input's `name` attribute&nbsp; &nbsp; &nbsp; const input = document.createElement("input");&nbsp; &nbsp; &nbsp; input.type = "text";&nbsp; &nbsp; &nbsp; input.name = "field" + ++totalFieldsCreated;&nbsp; &nbsp; &nbsp; input.value = "";&nbsp; &nbsp; &nbsp; // Creates an anchor element with the `remove_button` class&nbsp; &nbsp; &nbsp; const a = document.createElement("a");&nbsp; &nbsp; &nbsp; a.href = "javascript:void(0);";&nbsp; &nbsp; &nbsp; a.classList.add("remove_button");&nbsp; &nbsp; &nbsp; a.title = "remove";&nbsp; &nbsp; &nbsp; a.innerHTML = "Remove";&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; // Adds the new elements to the DOM, and increments `currentFieldCount`&nbsp; &nbsp; &nbsp; const div = document.createElement("div");&nbsp; &nbsp; &nbsp; div.appendChild(input);&nbsp; &nbsp; &nbsp; div.appendChild(a);&nbsp; &nbsp; &nbsp; $(wrapper).append(div);&nbsp; &nbsp; &nbsp; currentFieldCount++;&nbsp; &nbsp; &nbsp; // Logs the new values of both variables&nbsp;&nbsp; &nbsp; &nbsp; console.log(&nbsp; &nbsp; &nbsp; &nbsp; `currentFieldCount: ${currentFieldCount},`,&nbsp; &nbsp; &nbsp; &nbsp; `totalFieldsCreated ${totalFieldsCreated}`&nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }&nbsp; }});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="field_wrapper">&nbsp; <div>&nbsp; &nbsp; <input type="text" name="field1" value="" />&nbsp; &nbsp; <a href="javascript:void(0);" class="add_button" title="Add field">Add More</a>&nbsp; </div></div>

慕姐4208626

Math.random()在 js 而不是rand()在 php 中尝试,Math.floor(Math.random()*90000) + 10000会生成一个五位数的随机数,希望这会有所帮助$('.rand').attr('name',"fields["+Math.floor(Math.random()*90000) + 10000+"]")$('.add_button').click(function(e){$('.field_wrapper').append('<div><input type="text" name=fields['+Math.floor(Math.random()*90000) + 10000+'] value=""/><a href="javascript:void(0);" class="remove_button">Remove</a></div>')})$(document).on('click','.remove_button',function(e){&nbsp; &nbsp; &nbsp;$(this).parent().remove()})<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script><div class="field_wrapper">&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <input type="text" class="rand" value=""/>&nbsp; &nbsp; &nbsp; &nbsp; <a href="javascript:void(0);" class="add_button" title="Add field">Add More</a>&nbsp; &nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP