У меня есть макет, подобный этому:
<div id="..."><img src="..."></div>
и хотел бы использовать селектор jQuery для выбора дочернего элемента img
внутри div
при щелчке.
Чтобы получить div
, у меня есть этот селектор:
$(this)
Как я могу получить дочерний элемент img
с помощью селектора?
Конструктор jQuery принимает второй параметр context
, который может использоваться для переопределения контекста выделения.
jQuery("img", this);
Это то же самое, что использовать .find()
следующим образом:
jQuery(this).find("img");
Если желаемые imgs являются только прямыми потомками щелкнутого элемента, вы также можете использовать .children()
jQuery(this).children("img");
Вы также можете использовать
$(this).find('img');
который вернет все img
, которые являются потомками div
$(this).children('img')
будет лучше. например, <div><img src="..." /><div><img src="..." /></div></div>
потому что предположительно пользователь хочет найти imgs 1-го уровня.
Если вам нужно получить первый img
, который находится ровно на одном уровне, вы можете сделать
$(this).children("img:first")
:first
только с « на ровно один уровень » или с первым « img
который был найден?
.children()
- это то, откуда происходит «вниз ровно на один уровень», а :first
- это то, откуда пришло «первое».
Если вашему тегу DIV сразу следует тег IMG, вы также можете использовать:
$(this).next();
Прямые дети
$('> .child', this)
Вы можете найти все img-элементы родительского div, как показано ниже
$(this).find('img') or $(this).children('img')
Если вам нужен определенный элемент img, вы можете написать вот так
$(this).children('img:nth(n)')
// where n is the child place in parent list start from 0 onwards
Ваш div содержит только один элемент img. Итак, для этого ниже верно
$(this).find("img").attr("alt")
OR
$(this).children("img").attr("alt")
Но если ваш div содержит больше элемента img, как показано ниже
<div class="mydiv">
<img src="test.png" alt="3">
<img src="test.png" alt="4">
</div>
то вы не можете использовать верхний код, чтобы найти значение alt второго элемента img. Поэтому вы можете попробовать следующее:
$(this).find("img:last-child").attr("alt")
OR
$(this).children("img:last-child").attr("alt")
В этом примере показано общее представление о том, как вы можете найти фактический объект в родительском объекте. Вы можете использовать классы для дифференциации вашего дочернего объекта. Это легко и весело. то есть.
<div class="mydiv">
<img class='first' src="test.png" alt="3">
<img class='second' src="test.png" alt="4">
</div>
Вы можете сделать это, как показано ниже:
$(this).find(".first").attr("alt")
и более конкретным образом:
$(this).find("img.first").attr("alt")
Вы можете использовать find или children, как указано выше. Подробнее посетите Children http://api.jquery.com/children/ и найдите http://api.jquery.com/find/. Пример http://jsfiddle.net/lalitjs/Nx8a6/
Способы обращения к ребенку в jQuery. Я суммировал его в следующем jQuery:
$(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
Попробуйте этот код:
$(this).children()[0]
$($(this).children()[0])
.
Не зная идентификатор DIV, я думаю, что вы можете выбрать IMG следующим образом:
$("#"+$(this).attr("id")+" img:first")
Вы можете использовать один из следующих способов:
1 find():
$(this).find('img');
2 детей():
$(this).children('img');
jQuery each
- один из вариантов:
<div id="test">
<img src="testing.png"/>
<img src="testing1.png"/>
</div>
$('#test img').each(function(){
console.log($(this).attr('src'));
});
Вы можете использовать Child Selecor для ссылки на дочерние элементы, доступные в родительском.
$(' > img', this).attr("src");
И ниже, если у вас нет ссылки на $(this)
, и вы хотите ссылаться на img
, доступную в div
из другой функции.
$('#divid > img').attr("src");
Также это должно работать:
$("#id img")
this
У вас может быть 0 до многих тегов <img>
внутри вашего <div>
.
Чтобы найти элемент, используйте .find()
.
Чтобы сохранить код в безопасности, используйте .each()
.
Использование .find()
и .each()
вместе предотвращает пустые ссылочные ошибки в случае 0 <img>
элементов, а также позволяет обрабатывать несколько элементов <img>
.
// 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);
});
});
#mydiv {
text-align: center;
vertical-align: middle;
background-color: #000000;
cursor: pointer;
padding: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="mydiv">
<img src="" width="100" height="100"/>
</div>
$("body").off("click", "#mydiv").on("click", "#mydiv", function() {
Здесь функциональный код, вы можете запустить его (это простая демонстрация).
Когда вы нажимаете кнопку DIV, вы получаете изображение из разных методов, в этой ситуации "this" - это DIV.
$(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)'));
});
});
.the_div{
background-color: yellow;
width: 100%;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my_div" class="the_div">
<img src="...">
</div>
Надеюсь, что это поможет!
$(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)'));
});
});
.the_div{
background-color: yellow;
width: 100%;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my_div" class="the_div">
<img src="...">
</div>