// Set the click handler on your div
$("body").off("click", "#mydiv").on("click", "#mydiv", function() {
// Find the image using.find() and .each()
$(this).find("img").each(function() {
var img = this; // "this" is, now, scoped to the image element
// Do something with the image
$(this).animate({
width: ($(this).width() > 100 ? 100 : $(this).width() + 100) + "px"
}, 500);
});
});
$(document).ready(function() {
// When you click the DIV, you take it with "this"
$('#my_div').click(function() {
console.info('Initializing the tests..');
console.log('Method #1: '+$(this).children('img'));
console.log('Method #2: '+$(this).find('img'));
// Here, i'm selecting the first ocorrence of <IMG>
console.log('Method #3: '+$(this).find('img:eq(0)'));
});
});
$(this).find("img"); // any img tag child or grandchild etc...
$(this).children("img"); //any img tag child that is direct descendant
$(this).find("img:first") //any img tag first child or first grandchild etc...
$(this).children("img:first") //the first img tag child that is direct descendant
$(this).children("img:nth-child(1)") //the img is first direct descendant child
$(this).next(); //the img is first direct descendant child
128
您可以使用以下任一方法:
1 find():
$(this).find('img');
2 children():
$(this).children('img');
1
$(document).ready(function() {
// When you click the DIV, you take it with "this"
$('#my_div').click(function() {
console.info('Initializing the tests..');
console.log('Method #1: '+$(this).children('img'));
console.log('Method #2: '+$(this).find('img'));
// Here, i'm selecting the first ocorrence of <IMG>
console.log('Method #3: '+$(this).find('img:eq(0)'));
});
});
16 回答
如果您的DIV标记后面紧跟IMG标记,您还可以使用:
您可以使用Child Selecor引用父级中可用的子元素 .
以下是如果您没有引用
$(this)
并且您想在div
中引用其他函数中的img
.在不知道DIV的ID的情况下,我认为你可以选择这样的IMG:
您的
<div>
中可能包含0到多个<img>
标签 .要查找元素,请使用
.find()
.为确保您的代码安全,请使用
.each()
.同时使用
.find()
和.each()
可防止0<img>
元素的空引用错误,同时还允许处理多个<img>
元素 .这应该工作:
这是一个功能代码,你可以运行它(这是一个简单的演示) .
单击DIV时,您可以从一些不同的方法获得图像,在这种情况下,“this”是DIV .
希望能帮助到你!
直接的孩子是
试试这段代码:
你也可以使用
这将返回作为
div
的后代的所有img
您可以在下面找到父div的所有img元素
如果你想要特定的img元素,你可以像这样写
你的div只包含一个img元素 . 所以对于这个,下面是正确的
但是如果你的div包含更多img元素,如下所示
那么你不能使用高位代码来找到第二个img元素的alt值 . 所以你可以尝试这个:
此示例显示了如何在父对象中查找实际对象的一般概念 . 您可以使用类来区分子对象 . 这很简单有趣 . 即
你可以这样做:
更具体的是:
您可以使用上面代码中的查找或子项 . 更多访问儿童http://api.jquery.com/children/和查找http://api.jquery.com/find/ . 见例子http://jsfiddle.net/lalitjs/Nx8a6/
jQuery的
each
是一个选项:jQuery构造函数接受名为context的第二个参数,该参数可用于覆盖选择的上下文 .
这与使用.find()相同:
如果你想要的imgs是 only 被点击元素的直接后代,你也可以使用.children():
如果你需要得到第一个
img
,它只是一个级别,你可以做到在jQuery中引用一个孩子的方法 . 我在以下jQuery中总结了它:
您可以使用以下任一方法:
1 find():
2 children():