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");

为了方便调试,我把title输入的id改成了包含它的class(也就是title)。所以似乎我应该能够使用代码访问它$('#pid'+id+'-title')。然而,事实并非如此。相反,使用的结果$("#pid"+id+"-title")toSource()({context:({}), selector:"#pid0-title"}). 顺便说一下,0 是正确的 ID。

我觉得我一定遗漏了一些关于 JQuery 和动态元素的明显内容。我显然找不到我的对象的原因是什么?

4

3 回答 3

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());

例子

于 2012-06-09T00:36:44.857 回答
1

您的 id 中有引号,也有重复的 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 选择并获取如图所示的值,您的 id 中的撇号正在杀死代码。

于 2012-06-09T00:08:38.530 回答
1

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='' />" +
"<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 所提到的,您不应该IDdocument.

input.categoryinput.author有相同的ID

请参阅相关文档,其中内容为:

... ID 属性可用于唯一标识其元素。

于 2012-06-09T00:19:06.027 回答