好的,我正在动态地创建隐藏的输入字段,如下所示:
$("<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");为了便于调试,我将title输入的id更改为包含它的class (即title)。因此,似乎我应该能够使用代码$('#pid'+id+'-title')访问它。然而,情况并非如此。相反,使用$("#pid"+id+"-title")toSource()的结果是({context:({}), selector:"#pid0-title"})。顺便说一下,0是正确的ID。
我觉得我一定是遗漏了一些关于JQuery和动态元素的显而易见的东西。我显然找不到对象的原因是什么?
发布于 2012-06-09 08:36:45
你可以通过这样的方式尝试,更加清晰有序:
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
发布于 2012-06-09 08:08:39
您的in中有引号,也有重复的in,这两个in都无效。请只使用唯一的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进行选择并获得值。如图所示,ID中的撇号正在杀死代码。
发布于 2012-06-09 08:19:06
您的输入没有获得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 Watkins提到的,你不应该在document上复制ID。
input.category和input.author具有相同的ID。
请参阅相关的documentation,其中的内容为:
...an ID属性可用于唯一标识其元素。
https://stackoverflow.com/questions/10957332
复制相似问题