Вопрос

У меня есть макет, похожий на этот:

<div id="..."><img src="..."></div>

и хотел бы использовать селектор jQuery для выбора дочернего элемента img внутри div по щелчку.

Чтобы получить div, у меня есть этот селектор:

$(this)

Как мне забрать ребенка img с помощью селектора?

Это было полезно?

Решение

Конструктор jQuery принимает второй параметр с именем context , который может использоваться для переопределения контекста выбора.

jQuery("img", this);

Что аналогично использованию .find() следующим образом:

jQuery(this).find("img");

Если нужные вам изображения являются только прямыми потомками выбранного элемента, вы также можете использовать .children() :

jQuery(this).children("img");

Другие советы

Вы также можете использовать

$(this).find('img');

который вернул бы все img, которые являются потомками div

Если вам нужно получить первый img уровень ниже ровно на один уровень, вы можете сделать

$(this).children("img:first")

Если за вашим тегом DIV сразу же следует тег IMG, вы также можете использовать:

$(this).next();

direct children - это

$('> .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>

тогда вы не можете использовать верхний код для поиска альтернативного значения второго элемента 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")

Попробуйте этот код:

$(this).children()[0]

Вы можете использовать любой из следующих методов:

1 find ():

$(this).find('img');

2 ребенка ():

$(this).children('img');

jQuery's 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")

Вот функциональный код, вы можете его запустить (это простая демонстрация).

Когда вы нажимаете DIV, вы получаете изображение разными способами, в этой ситуации «это» - это 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>

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top