使用 HTML/Javascript 访问动态创建的 div 中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11547574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:37:15  来源:igfitidea点击:

Accessing elements inside dynamically created divs with HTML/Javascript

javascriptjqueryhtmljquery-selectors

提问by cdarwin

I'm quite new to javascript and JQuery programming. Usually, to access elements I give them an id, so I can get them like $("#"+id).blabla().

我对 javascript 和 JQuery 编程很陌生。通常,为了访问元素,我给它们一个 id,这样我就可以得到它们$("#"+id).blabla().

But now I need to dynamically create a div, and access elements inside it.

但现在我需要动态创建一个 div,并访问其中的元素。

Something like

就像是

<div id="automaticallyGeneratedId">
   <div ???></div> <!-- first div -->
   <div ???></div> <!-- second div -->
</div>

What are the best practices to access and identify each of the inner divs? I generate another id for them? Or what?

访问和识别每个内部 div 的最佳实践是什么?我为他们生成另一个 id?要不然是啥?

I don't have the theory of selectors fully clear.

我没有完全清楚选择器的理论。

edit: modified the question from identifying a single inner div to identifying divs amongs many of them

编辑:将问题从识别单个内部 div 修改为在其中许多 div 中识别 div

回答by thecodeparadox

You can maintain a pattern when you're generating id. For example:

您可以在生成id. 例如:

if you always generate idlike: myid1, myid2,myid3...

如果你总是生成id像:myid1, myid2, myid3...

<div id="myid1">
   <div></div>
</div>

<div id="myid2">
   <div></div>
</div>

......

then you can try:

那么你可以尝试:

$('div[id^=myid]').find('div').foo();

OR

或者

$('div[id^=myid] div').foo();

Here, ^=is start with selector, so div[id^=myid]will select divwhose idstart with myid.

在这里,^=是选择开始,所以div[id^=myid]会选择divid与开始myid

You can also use Contain word selector which is ~=and use like $('div[id~=myid]'). This will select divwith idcontains word myid.

您还可以使用包含单词选择器,它是~=和使用 like $('div[id~=myid]')。这将选择divwith idcontains word myid

Instead of idif you want to use other attribute eg. namethen change selector like:

而不是id如果你想使用其他属性,例如。name然后更改选择器,如:

$('div[name^=myid]')or $('div[name~=myid]').

$('div[name^=myid]')$('div[name~=myid]')

回答by ChrisThompson

It's usually a good practice that if you already have a reference to that outer div to just search from there using find.

如果您已经拥有对该外部 div 的引用,则可以使用 find 从那里进行搜索,这通常是一个很好的做法。

You can give it an id, or if you want to use a more general approach you can use classes.

你可以给它一个 id,或者如果你想使用更通用的方法,你可以使用类。

<div class="subdiv">...


$('#automaticallyGeneratedId').find('div.subdiv')

回答by Florian Margaine

Usually, when you create them, you can assign event handlers and the likes straight on them. Like this:

通常,当您创建它们时,您可以直接为它们分配事件处理程序等。像这样:

var div = $( '<div></div>' );
div.on( 'click', function() {
    // Do something when the generated div is clicked
});

// Then, add it to the DOM
$( 'body' ).append( div );

You don't need to bother selecting them with ID or classes, they're already available in your code.

您无需费心使用 ID 或类来选择它们,它们已经在您的代码中可用。

Another way is to use event bubbling to handle newly created elements of the same class. A good link about this is this one: http://beneverard.co.uk/blog/understanding-event-delegation/

另一种方法是使用事件冒泡来处理同一类的新创建元素。关于这个的一个很好的链接是这个:http: //beneverard.co.uk/blog/understanding-event-delegation/

回答by Perpetual Infinity

If you cache the divs you could use something like:

如果您缓存 div,您可以使用以下内容:

var myDiv1Child = $('div', myDiv1);

回答by Ken Mumo

Create a delegated listener and within the listener you can find the element by doing this

创建一个委托侦听器,在侦听器中,您可以通过执行此操作找到该元素

//If a div inside the parent is clicked then execute the function within
$('.PARENT_CLASS').click("div", function(){
//This variable holds all the elements within the div
var rows = document.querySelector('.PARENT_CLASS').getElementsByTagName('div');
for (i = 0; i < rows.length; i++) {
    rows[i].onclick = function() {
        console.log(this);  //The element you wish to manipulate
    }
  }
});

回答by user1475195

Many ways you can create an element and give him an Id or Class, or use the DOM to access it..

您可以通过多种方式创建元素并为其提供 Id 或 Class,或者使用 DOM 访问它。

$("html").prepend('<div id="foo"></div>');
$("#foo").doSomething();

another way

其他方式

$("#automaticallyGeneratedId").find("div").doSomething();

回答by Marco de Wit

To access the div in the element with the id:

要使用 id 访问元素中的 div:

$("#automaticallyGeneratedId div").whatever