Как получить детей из селектора $(this)?
У меня есть макет, похожий на этот:
<div id="..."><img src="..."></div>
и хотел бы использовать селектор jQuery, чтобы выбрать дочерний img
внутри div
по щелчку.
Чтобы получить div
У меня есть этот селектор:
$(this)
Как я могу получить ребенка img
используя селектор?
19 ответов
Конструктор jQuery принимает второй параметр с именем context
который может быть использован для переопределения контекста выбора.
jQuery("img", this);
Что так же, как использование .find()
как это:
jQuery(this).find("img");
Если желаемые imgs являются прямыми потомками элемента, по которому щелкнули, вы также можете использовать .children()
:
jQuery(this).children("img");
Вы также можете использовать
$(this).find('img');
который вернул бы все img
ы, которые являются потомками div
Если вам нужно получить первый img
это ровно на один уровень, вы можете сделать
$(this).children("img:first")
Если за вашим тегом DIV сразу же следует тег IMG, вы также можете использовать:
$(this).next();
Вы можете найти все элементы 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>
тогда вы не можете использовать верхний код, чтобы найти альтернативное значение второго элемента 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, как указано выше. Для получения дополнительной информации посетите Дети 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
Не зная ID DIV, я думаю, вы можете выбрать IMG следующим образом:
$("#"+$(this).attr("id")+" img:first")
Вы можете использовать любой из следующих методов:
1 найти ():
$(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");
Вот функциональный код, вы можете запустить его (это простая демонстрация).
Когда вы щелкаете по 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>
Надеюсь, поможет!
Вы можете иметь от 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>
$(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>
Если ваш img является первым элементом внутри div, попробуйте
$(this.firstChild);
$( "#box" ).click( function() {
let img = $(this.firstChild);
console.log({img});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box"><img src="https://picsum.photos/seed/picsum/300/150"></div>
С собственным javascript вы можете использовать
если у вас более одного тега изображения, используйте
this.querySelectorAll("img")
если только один тег изображения, то мы
this.querySelector("img")
Вы могли бы использовать
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
$(this).find('img');
</script>