1. 程式人生 > >在javascript中用for迴圈動態建立的input獲取其內容的方法

在javascript中用for迴圈動態建立的input獲取其內容的方法

 

問題:

$("#v_m").click(function(){
			 var  myselect=document.getElementById("v_m");
			 var index=myselect.selectedIndex ;
			 var option = myselect.options[index].text;
			 
			 var html = "";
			 for( var i = 0; i < option; i++ ) 
			 {
				 var j = i+1;
				 html += "<tr >";
				 html += "<td style="+'width:75px;height:30px;font-size:16px'+">內容"+j+"</td>";
				 html +=     "<td><input name="+'neirong'+" type="+'text'+" style="+'width:350px;height:30px;font-size:16px'+" id="+'neirong'+"></td>";
				 html += "</tr>";
			 }
			 $("#nnnn").html(html);

如何獲取input中的值呢?

 

起初百度發現介紹瞭如下方法:

        alert($("#neirong").length);
		$("#neirong").each(function() {
            neirong += $(this).val+"++";  //++為分隔符
        });

但是該方法只能獲取第一個input裡的內容無法獲取之後的input內容,因此不能使用。

 

產生上面問題的原因是在html中為一個標籤起的id是為了唯一標識這個標籤的,也就是說一個id只能標記一個標籤,如果想用同一個東西來標記多個標籤那麼我們可以使用class或者下面的name。

 

下面這種方法可以正確獲得所有input中的內容:

        alert($("input[name='neirong']").length);
		$("input[name='neirong']").each(function() {
            neirong += $(this).val()+"+"; 
        });