我点击按钮时使用jQuery创建一个新元素,功能如下:
function insert_ordered_group() {
var template =
'<div class="row recipient-group">' +
'<div class="col-sm-12 group-name-row handle">' +
'<div class="dropdown">' +
'<a data-toggle="dropdown" href="#"><span class="group-name">Group One</span><span class="glyphicon glyphicon-triangle-bottom"></span></a>' +
'<ul class="dropdown-menu">' +
'<li class="rename-group-tool">Rename Group</li>' +
'<li class="add-group-recipient">Add Recipient</li>' +
'<li class="remove-group-tool">Delete Group</li>' +
'</ul>' +
'</div>' +
'</div>' +
'</div>';
// Add HTML to recipient form
$('#ordered_recipients_sortable').append(template);
return true;
}
而不是返回true,是否可以返回对新创建的对象的引用,以便我可以在DOM中进一步操作它?由于此函数的动态特性,我不希望为每个元素生成一个ID,然后再引用它。
我试过了:
var test = $('#ordered_recipients_sortable').append(template);
console.log(test);
但是,只返回#ordered_recipients_sortable而不是新元素。
谢谢!
答案 0 :(得分:1)
您只需使用appendTo
,它会返回附加的元素,而不是附加到
var test = $(template).appendTo('#ordered_recipients_sortable')
答案 1 :(得分:1)
试试这个:
function insert_ordered_group() {
var template =
'<div class="row recipient-group">' +
'<div class="col-sm-12 group-name-row handle">' +
'<div class="dropdown">' +
'<a data-toggle="dropdown" href="#"><span class="group-name">Group One</span><span class="glyphicon glyphicon-triangle-bottom"></span></a>' +
'<ul class="dropdown-menu">' +
'<li class="rename-group-tool">Rename Group</li>' +
'<li class="add-group-recipient">Add Recipient</li>' +
'<li class="remove-group-tool">Delete Group</li>' +
'</ul>' +
'</div>' +
'</div>' +
'</div>';
// Add HTML to recipient form
var appendTo = $('#ordered_recipients_sortable');
appendTo.append(template);
return appendTo.find(".row.recipient-group:last-of-type")
}
jsfiddle:https://jsfiddle.net/zxv4xszb/2/
这将始终添加最后一个。
答案 2 :(得分:0)
@adeneo提供的答案正是我所寻找的,比我在寻找时找到的解决方案更可取,但是,这确实有效:
var new_element = $("#ordered_recipients_sortable .recipient-group:last-child");