2012-06-09 27 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属性可以用来唯一标识的元素。