$ (이) 선택기의 자녀를 얻는 방법은 무엇입니까?
-
08-07-2019 - |
문제
이와 비슷한 레이아웃이 있습니다.
<div id="..."><img src="..."></div>
jQuery 선택기를 사용하여 자식을 선택하고 싶습니다. img
내부 div
클릭.
얻기 위해 div
, 나는이 선택기를 가지고있다 :
$(this)
어떻게 아이를 얻을 수 있습니까? img
선택기 사용?
해결책
jQuery 생성자는 호출 된 두 번째 매개 변수를 허용합니다 context
선택의 컨텍스트를 무시하는 데 사용할 수 있습니다.
jQuery("img", this);
사용과 동일합니다 .find()
이와 같이:
jQuery(this).find("img");
당신이 원하는 IMG가 있다면 뿐 클릭 한 요소의 직접 후손 인 경우 .children()
:
jQuery(this).children("img");
다른 팁
당신은 또한 사용할 수 있습니다
$(this).find('img');
모든 것을 반환 할 것입니다 img
후손 인 s div
첫 번째를 가져와야한다면 img
그것은 정확히 한 레벨 이하입니다.
$(this).children("img:first")
DIV 태그와 즉시 IMG 태그가있는 경우 다음을 사용할 수도 있습니다.
$(this).next();
그만큼 직접 아이들은입니다
$('> .child', this)
아래와 같이 부모 div의 모든 IMG 요소를 찾을 수 있습니다.
$(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 요소의 ALT 값을 찾을 수 없습니다. 그래서 당신은 이것을 시도 할 수 있습니다 :
$(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")
위의 코드로 찾거나 어린이를 사용할 수 있습니다. 더 많은 방문 아이들 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
DIV의 ID를 알지 못하고 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'));
});
당신이 사용할 수있는 어린이 셀레코 부모 내에서 사용 가능한 아동 요소를 참조합니다.
$(' > img', this).attr("src");
그리고 아래는 당신이 $(this)
그리고 당신은 참조하고 싶습니다 img
a 내에서 사용할 수 있습니다 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>
.
요소를 찾으려면 a를 사용하십시오 .find()
.
코드를 안전하게 유지하려면 a를 사용하십시오 .each()
.
사용 .find()
그리고 .each()
함께 0의 경우 NULL 참조 오류를 방지합니다. <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>