js document.createElement 动态添加input与A标签的几个问题

本文探讨了在IE7浏览器中使用JavaScript动态创建HTML元素时遇到的问题,并提供了具体的解决方案。针对input元素的name属性无法正确设置及点击事件绑定失败等问题,文章给出了详细的解决步骤。
部署运行你感兴趣的模型镜像

 页面源码

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

		<title>ccccc</title>

	</head>
	<body>
		<div class="place">
			<div id="board" style="padding-left: 15px">

				<form action="/test/asc.do?m=create" method="post"
					onsubmit="return check2();">
					<table class="add">

						<td align="right">
						</td>
						<td align="left">
							<span id="upload">
								<div id="div_0">
									<input type="text" style="height: 16px" size="30"
										name="configure" />
									<a href='javascript:void(0)' onclick="removeInput2('div_0')">删除</a>
								</div> </span>
						</td>
						</tr>
						<tr>
							<td colspan="4" class="add">
								<input type="button" name="button" value="ADD"
									onclick="createInput()">
								<input type="button" name="button" value="ADD2"
									onclick="createInput2()">
								<input type="button" name="button" value="cs" onclick="cs()" />
							</td>
						</tr>
						<tfoot>
							<tr>
								<td></td>
								<td>
									<input type="text" name="userId2" />

									<input type="submit" class="button" id="Submit1" value="确定" />
								</td>
							</tr>
						</tfoot>
					</table>
</html>
</div>
</div>
<script>
			var div0_outerHTML=document.getElementById("div_0").outerHTML;
         	 var i=1; 
            
            function createInput2(){
           		 alert(div0_outerHTML);
            	var div_outerHTML = div0_outerHTML.replace(/_0/g, "_"+i);
				var shtml=document.getElementById("upload").innerHTML;
				document.getElementById("upload").innerHTML = shtml + div_outerHTML;
            	i++;
            }
            
          function removeInput2(DIVID){
          var aElement = document.getElementsByName("configure"); 
          if(aElement.length==1){
            	alert("最后的数据 不要删除");
          	return ;
          }
          	 document.getElementById(DIVID).outerHTML="";
          }
          
          function createInput(){   
	             var p=document.createElement("div"); 
	             p.id="div"+i;
	             var aElement=document.createElement("input");   
	             //aElement.name="configure"; 
	             aElement.setAttribute("name","configure");
	             aElement.id="configure";
	             aElement.type="text"; 
	             aElement.size="30"; 
	           
            var A = document.createElement("A");  
	            A.onclick = function (){removeInput(p.id);}; 
				A.setAttribute("href","javascript:void(0)");   
				A.appendChild(document.createTextNode("删除"));  
				p.appendChild(aElement); 
			    p.appendChild(A);  
             if(document.getElementById("upload").appendChild(p) == null) 
                { 
                      return false; 
                 } 
                    i++;
               return true; 
          } 
             function removeInput(divid){ 
               var aElement = document.getElementById("upload");
               var parent= document.getElementById(divid);
               alert(divid);
               alert(parent)
               alert(parent.id);
                if(aElement.removeChild(parent) == null) {
                    return false; 
                }
                return true;   
            } 
      
    function check2(){ 
              var aElement = document.getElementsByName("configure"); 
              alert(aElement);
              alert(aElement.length);
              for(j=0;j<aElement.length;j++){
              	alert(aElement[j].value)
             } 
        
          return true;
       } 
   
	function cs(){
	alert( document.getElementById("upload").outerHTML);
	}
	
	
 </script>


</body>
</html>

        

 

 document.createElement 动态添加 input与A有如下两个问题(IE7)

 

  1.  var aElement=document.createElement("input");  
             //aElement.name="configure";
             aElement.setAttribute("name","configure");
            上述方法 name属性无法赋值

    解决方案:aElement.id="configure"; 设置Id属性

2  A.setAttribute("onclick","removeInput(p.id)");  

 解决方案:   A.onclick = function (){removeInput(p.id);};

您可能感兴趣的与本文相关的镜像

Facefusion

Facefusion

AI应用

FaceFusion是全新一代AI换脸工具,无需安装,一键运行,可以完成去遮挡,高清化,卡通脸一键替换,并且Nvidia/AMD等显卡全平台支持

<think> 我们有一个动态添加输入框的代码,现在需要添加下拉框的动态添加设计。原有的代码是每点击一次添加一个文本输入框,现在要求同时支持下拉框的添加(即可以添加输入框或下拉框,由用户选择添加哪种控件)。 思路: 1. 在页面上提供两个按钮:一个用于添加输入框,一个用于添加下拉框(或者提供一个选择器让用户选择要添加的控件类型,然后点击一个添加按钮)。 2. 修改addInput函数,使其能够根据类型创建不同的控件。 但用户只要求添加下拉框的动态添加设计,并没有明确是要同时支持两种还是一种。不过从问题描述来看,用户希望扩展原有的代码,使其能够添加下拉框。 这里我们假设用户希望: - 保留原有的添加输入框功能 - 新增一个功能:添加下拉框 因此,我们可以: 1. 创建两个按钮:一个添加输入框,一个添加下拉框。 2. 分别编写两个函数,或者修改addInput函数使其能够接受参数(类型)。 为了清晰,我们可以: 方案一:创建两个函数,一个用于添加输入框,一个用于添加下拉框。 方案二:修改addInput函数,传入一个参数表示类型,然后根据类型创建不同的元素。 这里采用方案二,这样代码复用性更高。 修改步骤: 1. 修改按钮:将原来的按钮改为两个按钮(或者一个选择器+一个按钮),这里为了简单,我们使用两个按钮。 2. 修改addInput函数,增加一个参数type,可以是'text'或'select'。 3. 在函数内部,根据type创建不同的HTML字符串。 注意:计数器counter应该是共用的,因为不管是输入框还是下拉框,我们都希望它们有唯一的标识。 具体实现如下: 首先,在HTML添加两个按钮: <button onclick="addInput('text')">添加文本框</button> <button onclick="addInput('select')">添加下拉框</button> 然后,修改addInput函数: function addInput(type) { const container = document.getElementById("inputsContainer"); const newInput = document.createElement("div"); newInput.className = "input-container"; // 根据类型生成不同的HTML if (type === 'text') { newInput.innerHTML = ` <input type="text" placeholder="输入框 ${counter}" name="inputField${counter}"> `; } else if (type === 'select') { // 下拉框,这里我们给下拉框几个默认选项,也可以动态获取,但题目没有要求 newInput.innerHTML = ` <select name="selectField${counter}"> <option value="">请选择</option> <option value="option1">选项1</option> <option value="option2">选项2</option> <option value="option3">选项3</option> </select> `; } container.appendChild(newInput); counter++; // 计数器增加 } 这样,当用户点击“添加文本框”时,会添加一个文本输入框;当用户点击“添加下拉框”时,会添加一个下拉选择框。 但是,如果用户希望下拉框的选项是动态的(比如通过AJAX获取),那么就需要在创建下拉框后,再通过AJAX请求来填充选项。不过题目没有要求,所以暂时写死。 另外,注意原代码中有一个计数器counter,我们用它来确保每个输入框或下拉框的name属性唯一。 完整代码示例: HTML部分: <div id="inputsContainer"></div> <button onclick="addInput('text')">添加文本框</button> <button onclick="addInput('select')">添加下拉框</button> JavaScript部分: let counter = 1; function addInput(type) { const container = document.getElementById("inputsContainer"); const newInput = document.createElement("div"); newInput.className = "input-container"; if (type === 'text') { newInput.innerHTML = `<input type="text" placeholder="输入框 ${counter}" name="inputField${counter}">`; } else if (type === 'select') { newInput.innerHTML = ` <select name="selectField${counter}"> <option value="">请选择</option> <option value="option1">选项1</option> <option value="option2">选项2</option> <option value="option3">选项3</option> </select> `; } container.appendChild(newInput); counter++; } 注意:如果用户需要动态填充下拉选项,可以在创建下拉框元素后,使用AJAX请求数据,然后填充。这里不展开。 另外,如果希望每个下拉框的选项都是动态从服务器获取,那么就不能在innerHTML中写死选项,而是先创建select元素,然后通过JavaScript动态添加option。例如: function addInput(type) { // ... 前面的代码相同 if (type === 'text') { // ... 同上 } else if (type === 'select') { // 创建select元素 const select = document.createElement('select'); select.name = `selectField${counter}`; // 先添加一个默认选项 const defaultOption = document.createElement('option'); defaultOption.value = ''; defaultOption.textContent = '请选择'; select.appendChild(defaultOption); // 这里假设我们通过AJAX获取选项,但为了演示,我们用setTimeout模拟异步 // 实际中应该用fetch或XMLHttpRequest // 模拟异步获取选项 setTimeout(() => { // 假设从服务器获取的选项数组 const options = ['选项1', '选项2', '选项3']; options.forEach(opt => { const option = document.createElement('option'); option.value = opt; option.textContent = opt; select.appendChild(option); }); }, 0); // 实际AJAX请求可能需要时间 newInput.appendChild(select); } container.appendChild(newInput); counter++; } 但是,由于AJAX是异步的,所以选项会在请求返回后才出现。如果选项很多或者网络慢,用户可能会看到下拉框先是一个“请选择”,然后过一会儿才出现选项。 根据题目要求,我们不需要实现动态填充,所以使用写死的方式即可。 综上所述,我们修改了addInput函数,使其支持添加文本框和下拉框。 </think> 基于您提供的动态添加输入框代码,我将添加下拉框的动态添加功能,并解释实现原理: ### 动态添加下拉框的解决方案 ```javascript let counter = 1; // 元素计数器 // 添加输入框功能(保留原功能) function addInput() { const container = document.getElementById("inputsContainer"); const newInput = document.createElement("div"); newInput.className = "input-container"; newInput.innerHTML = ` <input type="text" placeholder="输入框 ${counter}" name="inputField${counter}"> `; container.appendChild(newInput); counter++; } // 新增:添加下拉框功能 function addDropdown() { const container = document.getElementById("inputsContainer"); const newDropdown = document.createElement("div"); newDropdown.className = "dropdown-container"; // 创建带选项的下拉框 newDropdown.innerHTML = ` <select name="dropdownField${counter}"> <option value="">-- 请选择 --</option> <option value="option1">选项1</option> <option value="option2">选项2</option> <option value="option3">选项3</option> </select> `; container.appendChild(newDropdown); counter++; } // 新增:动态加载下拉选项(可选功能) function loadDropdownOptions(selectElement, options) { options.forEach(option => { const optionElement = document.createElement("option"); optionElement.value = option.value; optionElement.textContent = option.label; selectElement.appendChild(optionElement); }); } ``` ### HTML部分需要添加按钮: ```html <button onclick="addInput()">添加输入框</button> <button onclick="addDropdown()">添加下拉框</button> <div id="inputsContainer"></div> ``` ### 实现说明: 1. **独立计数器**: - 使用共享的`counter`变量确保所有元素名称唯一 - 命名规则:`inputFieldN` 和 `dropdownFieldN`(N为计数器值) 2. **下拉框结构**: ```html <select name="dropdownField1"> <option value="">-- 请选择 --</option> <option value="option1">选项1</option> ... </select> ``` 默认包含空白选项防止误选[^1] 3. **动态加载选项(高级用法)**: ```javascript // 使用示例: const myOptions = [ { value: "optA", label: "选项A" }, { value: "optB", label: "选项B" } ]; const newDropdown = addDropdown(); loadDropdownOptions(newDropdown.querySelector("select"), myOptions); ``` 可从API获取数据动态填充选项 4. **表单提交处理**: 所有元素都包含`name`属性,表单提交时将自动包含: ```js // 获取所有下拉框的值 const dropdownValues = Array.from(document.querySelectorAll("select")) .map(select => select.value); ``` ### 使用示例效果: 初始状态: ``` [添加输入框] [添加下拉框] (空容器) ``` 点击"添加下拉框"后: ``` [添加输入框] [添加下拉框] <select> <option>--请选择--</option> <option>选项1</option> ... </select> ``` 再次点击"添加输入框": ``` [添加输入框] [添加下拉框] <select>...</select> <input type="text" placeholder="输入框1"> ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值