我试图通过$(this)调用动态创建的元素,是否可能?
例如:
$(".el").on("click",function(){
$("body").append("<div class='new'></div>");
// call class .new via $(this)
});
是否可以从$(&#34; .el&#34;)调用class .new 或者从另一个函数中调用$(&#34; .el&#34;)&#34; .new&#34;)
答案 0 :(得分:3)
如果不调用其他功能,则无法分配this
。无论如何,最好是缓存元素,将其保存在var中。您可以使用以下代码:
$(".el").on("click",function(){
var $el = $("<div class='new'></div>").appendTo('body');
// $el will be $('.new') and you can call jQuery function like that
// $el.addClass('work');
});
答案 1 :(得分:2)
您无法在此时重新分配this
,但您可以在创建变量时将新元素分配给变量。这样你就可以简单地使用new变量而不是关键字this。
$(".el").on("click",function(){
var newEl = $('<div class="new"></div>');
$("body").append(newEl);
});
另一方面,您可以在另一个函数中将新元素用作this
。为此,请使用call
或apply
函数。
someFunc.call(newEl); // Makes newEl become this inside the function
var someFunc = function(){
// this is now newEl within this scope
}
答案 2 :(得分:2)
$('.el').on('click',function(){
var mynewdiv = $('<div class="new"></div>');
$('body').append(mynewdiv);
//mynewdiv is your dynamically created element.
});
或
$('.el').on('click',function(){
var UniqueId = '_id'+ new Date().valueOf();
$('body').append('<div class="new" data-id="'+UniqueId+'"></div>');
// $('[data-id='+UniqueId+']') is your created element.
});