简体   繁体   English

如何访问动态创建的对象

[英]How to access a dynamically created object

I am creating an object dynamically. 我正在动态创建对象。 I am wondering how do I access it? 我想知道如何访问它? Some of these objects need to be hidden through other means than a click (programmatically, button clicks, links, etc). 其中一些对象需要通过其他方式隐藏,而不是单击(以编程方式,按钮单击,链接等)。 So I dont think I could use .on. 所以我认为我不能使用.on。 How would I go about accessing these to hide them? 我将如何访问这些以隐藏它们?

$(document).ready(function() {
$('body').append('<div id="testdiv">Test DIV</div>');

}); 

$('#testdiv').hide();

You reverse your logic. 您颠倒了逻辑。 Instead of .append() , you should use .appendTo() 而不是.append() ,你应该使用.appendTo()

var myRef = $("<div id=\"testdiv\">Test DIV</div>").appendTo( document.body );

That way, you can keep a reference to that newly created DOM node / jQuery object . 这样,您可以保留对新创建的DOM节点 / jQuery对象的引用。

myRef.hide();

It's always better to store a cached reference into a variable, so you can access a node from pure ECMA land , so to speak. 最好将缓存的引用存储到变量中,这样可以说可以从纯ECMA land访问节点。 The need to re-query for a DOM node, is just much less effiecient. 重新查询 DOM节点的需求效率低得多。

One word of caution: variables declared by var do only own function scope . 请注意: var声明的变量仅具有函数作用域 That means if you want to access that reference from "outside" of your ready handler , you would need to declare that variable in a parent context for instance. 这意味着,如果要从就绪处理程序的 “外部”访问该引用,则需要在父上下文中声明该变量。

What you've got already should work, except you'll need to move $('#testdiv').hide(); 你已经应该工作,除了你需要移动$('#testdiv').hide(); inside the document ready (so you're not calling it before the element is created). 在文档内部就绪(因此在创建元素之前不要调用它)。

The other answer is a cleaner way to do it, and the way that I would do it. 另一个答案是更清洁的方式,以及我这样做的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM