1

我正在尝试通过 $(this) 调用动态创建的元素,这可能吗?

例如:

$(".el").on("click",function(){
  $("body").append("<div class='new'></div>");
    // call class .new via $(this)
});

是否可以从 $(".el") 调用类 .new 或从另一个函数从 $(".new") 调用 $(".el")

4

3 回答 3

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');
});
于 2013-08-26T02:53:51.103 回答
2

此时您无法重新分配this,但您可以在创建新元素时将其分配给变量。这样您就可以简单地使用新变量而不是关键字 this。

$(".el").on("click",function(){
  var newEl = $('<div class="new"></div>');
  $("body").append(newEl);
});

另一方面,您可以像this在另一个函数中一样使用新元素。为此,您使用callorapply函数。

someFunc.call(newEl); // Makes newEl become this inside the function

var someFunc = function(){
  // this is now newEl within this scope
}
于 2013-08-26T02:43:23.153 回答
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.
});
于 2013-08-26T02:43:29.447 回答