2012-06-09 25 views
0

好的,我動態創建隱藏的輸入字段如下:獲得動態創建的元件

$("<input type='hidden' id=pid'"+postid+"-title name='posts["+postid+"][title]' value='' />" + 
    "<input type='hidden' id=pid'"+postid+"-body name='posts["+postid+"][body]' value='' />" + 
"<input type='hidden' id=pid'"+postid+"' class='category' name='posts["+postid+"][category]' value='' />" + 
"<input type='hidden' id=pid'"+postid+"' class='author' name='posts["+postid+"][author]' value='' />" 
).appendTo("#datatable"); 

爲了便於調試,我在CLUDE其類改變了標題輸入的ID(它是標題) 。因此,似乎我應該可以通過代碼$('#pid'+id+'-title')訪問它。但是,這並非如此。相反,使用$("#pid"+id+"-title")toSource()的結果是({context:({}), selector:"#pid0-title"})。 0,順便說一下,是正確的ID。

我覺得我必須缺少一些關於JQuery和動態元素的明顯的東西。我顯然無法找到我的對象的原因是什麼?

+0

你加倍類別和作者的ID,但是這不是問題 –

回答

2

您可以用這種方式試圖更加清晰有序:

var createInputs = function(postid) { 

    var 
     input = $('<input type="hidden" value="" />'), 
     createInput = function(id, type) { 
      return input.clone() 
        .addClass(type) 
        .attr('id', 'pid' + id + '-' + type) 
        .attr('name', 'posts[' + id + '][' + type + ']'); 
     }; 

    $() 
     .add(createInput(postid, 'title')) 
     .add(createInput(postid, 'body')) 
     .add(createInput(postid, 'category')) 
     .add(createInput(postid, 'autor')) 
     .appendTo('#datatable'); 

};  

createInputs(1); 

console.log($('#datatable').html()); 

example

+0

+'d this,nice one :) – Zuul

+0

@Zuul感謝您的評論 –

1

你在你的ID中有引號,你也有重複的ID,兩者都不是有效的。請你只使用具有可接受的字符一個唯一的ID(用字母開始,可以包含數字和下劃線,並且我忘記了可能是幾個人)

$("<input type='hidden' id='pid"+postid+"-title' name='posts["+postid+"][title]' value='' />" + 
    "<input type='hidden' id='pid"+postid+"-body' name='posts["+postid+"][body]' value='cccc' />" + 
"<input type='hidden' id='pid"+postid+"-category' class='category' name='posts["+postid+"][category]' value='' />" + 
"<input type='hidden' id='pid"+postid+"-author' class='author' name='posts["+postid+"][author]' value='' />").appendTo("#datatable"); 


alert($("#pid1-body").val()); 

jQuery的上述工作,我可以通過ID選擇並獲得價值如圖所示,ids中的撇號正在殺死代碼。

+0

有效字符的標識符[是](http://www.w3.org/TR/CSS21/syndata.html#characters)。 – Zuul

1

由於所有這些屬性錯位「單引號」,您的輸入未獲得ID屬性的值。

看到這個working Fiddle例子!

適應你的代碼這樣:

$("<input type='hidden' id='pid"+postid+"-title' name='posts["+postid+"][title]' value='' />" + 
"<input type='hidden' id='pid"+postid+"-body' name='posts["+postid+"][body]' value='' />" + 
"<input type='hidden' id='pid"+postid+"' class='category' name='posts["+postid+"][category]' value='' />" + 
"<input type='hidden' id='pid"+postid+"' class='author' name='posts["+postid+"][author]' value='' />" 
).appendTo("#datatable"); 

元素應該沒有任何問題,現在的選擇。


注: 正如@Jeff沃特金斯所說,你不應該在document複製ID秒。

input.categoryinput.author有相同的ID

請參閱相關的documentation,其中有這麼一句話:

... ID屬性可以用來唯一標識的元素。