[英]Get DOM Element with jQuery
I have a web page that is structured like this: 我有一个结构如下的网页:
<canvas id="myCanvas"></canvas>
@for(var i=0; i<10; i++) {
<div class="my-element">
<canvas></canvas>
</div>
}
This code generates one main canvas. 此代码生成一个主画布。 Below it, 10 other dynamically generated divs are being generated.
在它下面,正在生成10个其他动态生成的div。 In reality, this loop is just used to show that I have some code being dynamically generated.
实际上,此循环仅用于显示我有一些动态生成的代码。 The main thing to understand is the
my-element
piece. 要了解的主要是
my-element
。
In my javascript, I have the following: 在我的JavaScript中,我有以下内容:
$(function() {
var mainCanvas = document.getElementById('myCanvas');
initializeCanvas(mainCanvas); // This works.
var dynamicElements = $('.my-element');
for (var i=0; i<dynamicElements.length; i++) {
initializeCanvas($(dynamicElements[i])[0]); // This does not work
}
});
function initializeCanvas(canvas) {
// do stuff
}
The first call to initializeCanvas
works because I'm passing in an actual HTML Dom element. 因为我要传递一个实际的HTML Dom元素,所以对
initializeCanvas
的第一次调用有效。 But the second initializeCanvas
, which is called multiple times, fails because it's passing in something else. 但是第二次
initializeCanvas
多次调用失败,因为它传递了其他内容。 How do I get the same type of element as what's returned by document.getElementById in this case? 在这种情况下,如何获得与document.getElementById返回的元素相同类型的元素?
Thanks! 谢谢!
First of all, this doesn't make sense: $(dynamicElements[i])[0]
首先,这没有任何意义:
$(dynamicElements[i])[0]
You are getting jQuery element, unwrapping it, then wrapping again in jQuery... 您正在获取jQuery元素,将其展开,然后再次包装在jQuery中...
what you simply need to do is get canvas
from the element 您只需要从元素中获取
canvas
dynamicElements.eq(i).find('canvas')[0]
should do the job dynamicElements.eq(i).find('canvas')[0]
应该可以完成这项工作
You can't use the same element for this purpose. 为此,您不能使用相同的元素。 I suggest you to clone it.
我建议您克隆它。 Like;
喜欢;
var dynamicElements = $('.my-element').clone();
Also when you add more element with my-element class this will be messy. 另外,当您使用my-element类添加更多元素时,这将很混乱。 You should make sure to select only one element with $('.my-element') selection.
您应该确保仅选择$('。my-element')选择的一个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.