在 DOM 创建中将 jQuery 与原生 JS 结合起来
我正在重用我的旧应用程序,并且想要更改代码,因此我将构建的 DOM 结构应用到节点的类而不是它的 id。
下面是一段代码,正如您所看到的,我尝试将 jQuery(通过其类获取节点)与旧结构结合起来,但有些东西在这里无法正常工作。
是否可以像这样将 jQuery 和 JS 原生结合起来? 如果没有,还有其他方法可以完成我想做的事情吗?
var gamearea = $('<div/>', {
text': 'testarea',
class': 'gamearea'
}).appendTo('.memory:last');
alert("this.rows: " + this.rows);
for (var j = 0; j < this.rows; j++){
var box = document.createElement('div');
for (var i = 0; i < this.cols; i++){
var iterator = (this.cols * j) + i;
var img = document.createElement('img');
var aNod = document.createElement('a');
aNod.href = "#";
img.src = "pics/0.png";
aNod.appendChild(img);
box.appendChild(aNod);
}
gamearea.appendChild(box);
}
I'm reusing an old application of mine and want to change the code so I'm applying the DOM structure that I build up to a node's class instead of it's id.
Below is a piece of the code and as you can see I try to combine jQuery (getting the node by it's class) with the old structure, but something doesn't work properly here.
Is it possible to combine jQuery and JS native like this?
If not, is there another way to accomplish what I want to do?
var gamearea = $('<div/>', {
text': 'testarea',
class': 'gamearea'
}).appendTo('.memory:last');
alert("this.rows: " + this.rows);
for (var j = 0; j < this.rows; j++){
var box = document.createElement('div');
for (var i = 0; i < this.cols; i++){
var iterator = (this.cols * j) + i;
var img = document.createElement('img');
var aNod = document.createElement('a');
aNod.href = "#";
img.src = "pics/0.png";
aNod.appendChild(img);
box.appendChild(aNod);
}
gamearea.appendChild(box);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够通过将
gamearea.appendChild(box);
更改为gamearea[0].appendChild(box);
来使其工作,其背后的原因是您可以得到只需执行
obj[0]
即可获取 jQuery 扩展对象的裸 DOM 元素,其中obj
是像obj = $(... )
等等。代码中的appendChild
方法是裸 DOM 元素的方法。You should be able to get it working by changing
gamearea.appendChild(box);
togamearea[0].appendChild(box);
The reason behind that is you can get the bare DOM element for a jQuery extended object by simply doing
obj[0]
, whereobj
is a jQuery extended object obtained likeobj = $(...)
etc. And theappendChild
method in your code is a method of bare DOM element.