<div>
아래와 같이 4 개의 컨테이너가 있습니다.
<div class="parentBox">
<div class="childBox" id="20">
<div>some content with in this div</div>
<div>another div with more sontent</div>
</div>
</div>
childBox div 내에서 아무 곳이나 클릭 할 때 childBox ID를 jQuery 변수로 가져오고 싶습니다. 나는 나에게주는 다음을 시도했다undefined
$('.parentBox').click(function (event) {
var id = $(this).attr('id');
console.log(id);
});
나에게 부모를 준 이것은 기능이 아닙니다.
var id = $(this).parent().attr('id');
콘솔 로그에 공백이 표시되는 이것을 시도했습니다.
var id = event.target.id;
누군가 도와 주시겠습니까?
$('.parentBox').click(function (event) {
var id = $(this).attr('id');
console.log(id);
//does not work
console.log($(this).parnet().attr('id'));
//also does not work
console.log(event.target.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parentBox">
<div class="childBox" id="20">
<div>some content with in this div</div>
<div>another div with more sontent</div>
</div>
</div>
div를 .childBox
클릭 할 때 ID 를 원하는 경우 클래스 .childBox
에서 클릭 이벤트를 연결할 수 있습니다 .childBox
.
$('.childBox').click(function (event) {
var id = $(this).attr('id');
console.log(id);
});
편집하다:
.childBox
from .parentBox
이벤트 에 액세스하려면 다음을 수행하십시오.
$('.parentBox').click(function (event) {
var id = $(this).find('.childBox').attr('id');
console.log(id);
});
동적으로 자식을 추가 할 때 다음과 같이 부모 또는 문서 개체에 이벤트를 연결하는 것이 좋습니다.
$(document).on('click', '.childBox' , function() {
console.log($(this).attr('id'));
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다