使用“this”在节点的子节点上应用事件
我有一个函数可以动态创建 div 框并在其上放置一个事件。在框中我创建了一个 a 节点,并在其中创建了一个 img 节点。当我单击 a 节点时,事件将触发,并且背景图像将在另一个 div 上更改。下面你可以看到我的代码,就像现在一样,“this.src”指向 a 节点,这当然不起作用。
有没有办法指向 a 节点的子节点,即。该行的 img 节点?
var box = $('<div/>', {
'class': 'imgDiv',
'width': maxWidth,
'height': maxHeight,
}).appendTo('.windowContent');
var a = $('<a/>', {
'href': '#',
}).appendTo(box)
var img = $('<img/>', {
'src': 'pics/' + this.fileName,
'width': this.thumbWidth,
'height': this.thumbHeight,
}).appendTo(a);
$(a).click(function() {
$('#desktop').css("background-image", "url(" + this.src + ")");
});
I have a function that dynamically creates div boxes and put an event on them. In the box I create an a-node and inside that an img-node. When I click the a-node the event shall fire and the background image shall be changed on another div. Below you can see my code, and as it it now, 'this.src' points to the a-node, which of course doesn't work.
Is there a way to point at the a-node's child, ie. the img-node on that line?
var box = $('<div/>', {
'class': 'imgDiv',
'width': maxWidth,
'height': maxHeight,
}).appendTo('.windowContent');
var a = $('<a/>', {
'href': '#',
}).appendTo(box)
var img = $('<img/>', {
'src': 'pics/' + this.fileName,
'width': this.thumbWidth,
'height': this.thumbHeight,
}).appendTo(a);
$(a).click(function() {
$('#desktop').css("background-image", "url(" + this.src + ")");
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
this
确实会指向在单击处理程序内单击的锚点。您对此无能为力,但您的点击处理程序将在您的img
变量上形成一个闭包。这是你想要的吗?
编辑
正如 Felix 指出的, a 已经是一个 jQuery 对象,所以你可以简单地执行以下操作:
this
will indeed point to the anchor that was clicked inside of the click handler. There's nothing you can do about that, but your click handler will form a closure over yourimg
variable.Is this what you want?
EDIT
As Felix points out, a is already a jQuery object, so you can simply do:
是的,你可以这样做:
Yes, you can do with this:
我想你可以这样做:
I guess you could do: