生成/删除div时发生#id冲突

时间:2016-12-07 20:13:43

标签: javascript jquery

我正在尝试设置一个脚本,允许用户生成最多4个div(每个包含一个输入和一个跨度)以及删除它们的能力。

var i = 1;
$(".submit-source .add-source").click( function() {
	i++;
	source = jQuery('<div id="source-wrap-' + i + '" class="source-wrap" ><input name="source-' + i + '" type="text"/><span class="remove-source">remove</span></div>');
	source.insertAfter(".submit-source .source-wrap:last");
				
	if (i == 4) {
		$(".submit-source .add-source").hide();
	}
	else {
		$(".submit-source .add-source").show();
	}
} );
$(document).on("click", ".submit-source .remove-source", function() {
	i--;
	$(this).parent().remove();
				
	if (i == 4) {
		$(".submit-source .add-source").hide();
	}
	else {
		$(".submit-source .add-source").show();
	}
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="submit-source">
	<span>Add up to 4 different sources.</span>
	<div id="source-wrap-1" class="source-wrap" >
		<input name="source-1" type="text"/>
	</div>
	<span class="add-source">add input</span>
</div>

我遇到的问题是,例如,如果生成了4个div并且用户删除了第2个或第3个div然后生成了新的div,则最终会得到2个具有相同id的div(同样适用于在这些divs中输入名称。)

如何改进我的脚本,以便生成的输入检查以前的输入是否存在?例如,如果这个已经存在,它将不会生成新的#source-wrap-4,而是如果此div不存在或被删除则生成#source-wrap-3。

我不希望它超过#source-wrap-4(以及输入名称的source-4),因此我可以在检索数据时使用php轻松处理输入。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

通过将可用的ID保存在数组中,您可以确保不要重复使用任何不应该使用的内容。

此外,您的添加和删除功能中的if / then逻辑相同,因此它们被隔离以删除重复。

&#13;
&#13;
// Store available ids
var availableIDs = [2,3,4];

const NOT_AVAIL = "ID_UNAVAILABLE";

// This function returns the first element in the aray
// If the array no longer has any available elements,
// it returns "ID_UNAVAILABLE". You can incorporate that 
// into the code to ensure that only 4 elements can be made at max
function getID(){
  if(availableIDs.length > 0){  
    // return the first element in the array and remove that element
    // from the array
    return availableIDs.shift();
  } else {
    return NOT_AVAIL;
  }
}

$(".submit-source .add-source").click( function() {
    // Get the next available ID
    var newID = getID();
  
    // As long as the new ID is not "ID_UNAVAILABLE", proceed:
    if(newID !== NOT_AVAIL){
	  source = $('<div id="source-wrap-' + newID + 
                      '" class="source-wrap" ><input name="source-' + newID + 
                      '" type="text"/><span class="remove-source">remove</span></div>');
  
	  source.insertAfter(".submit-source .source-wrap:last");
     
      var theID = $(source).attr("id");
      var theLastChar = theID[theID.length - 1];
      
      // Test new element
      console.log("New element's ID is: " + theID, "Array now contains: " + availableIDs);
      hideShow();
    }
} );

$(document).on("click", ".submit-source .remove-source", function() {  
    var theID = $(this).parent()[0].getAttribute("id");
    var theLastChar = theID[theID.length - 1];
    $(this).parent().remove();
  
	availableIDs.push(theLastChar);
    console.log("ID to be put back into array is: " + theLastChar, 
                "Array now contains: " + availableIDs);		
    hideShow();
} );

// Common function used when adding and removing:
function hideShow(lastChar){
  var $setToWorkOn = $(".submit-source .add-source");
  (availableIDs.length === 0) ? $setToWorkOn.hide() : $setToWorkOn.show();
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="submit-source">
	<span>Add up to 4 different sources.</span>
	<div id="source-wrap-1" class="source-wrap" >
		<input name="source-1" type="text"/>
	</div>
	<span class="add-source">add input</span>
</div>
&#13;
&#13;
&#13;