이벤트를 발생시킨 요소의 ID 가져 오기
이벤트를 발생시키는 요소의 ID를 얻는 방법이 있습니까?
나는 다음과 같이 생각하고 있습니다.
<html>
<head>
<script type="text/javascript" src="starterkit/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a").click(function () {
var test = caller.id;
alert(test.val());
});
});
</script>
</head>
<body>
<form class="item" id="aaa">
<input class="title"></input>
</form>
<form class="item" id="bbb">
<input class="title"></input>
</form>
</body>
</html>
물론 , 이벤트가 첫 번째 양식에서 시작된 경우 , 그리고 두 번째 양식에서 이벤트가 시작된 경우 test
에는 var 에 id가 포함되어야합니다 ."aaa"
"bbb"
jQuery에서 event.target
항상 이벤트를 트리거 한 요소를 참조하며 여기서는 event
함수에 전달 된 매개 변수입니다. http://api.jquery.com/category/events/event-object/
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});
참고 또한 this
당신이 그것을에 jQuery를 기능을 사용하고자하는 경우 것 또한 작품,하지만하다는 jQuery를 객체는, 그래서 당신은 그것을 참조해야하지 $(this)
예 :
$(document).ready(function() {
$("a").click(function(event) {
// this.append wouldn't work
$(this).append(" Clicked");
});
});
참고로 이것을 시도하십시오! 효과가있다!
jQuery("classNameofDiv").click(function() {
var contentPanelId = jQuery(this).attr("id");
alert(contentPanelId);
});
다른 게시물에서 언급되었지만 이것을 철자하고 싶었습니다.
$(event.target).id
정의되지 않음
$(event.target)[0].id
id 속성을 제공합니다.
event.target.id
또한 id 속성을 제공합니다.
this.id
id 속성을 제공합니다.
과
$(this).id
정의되지 않았습니다.
물론 차이점은 jQuery 객체와 DOM 객체 사이에 있습니다. "id"는 DOM 속성이므로이를 사용하려면 DOM 요소 개체에 있어야합니다.
(그것은 나를 넘어 뜨 렸기 때문에 아마 다른 사람을 넘어 뜨렸을 것입니다)
모든 이벤트에 대해 jQuery에만 국한되지 않고 사용할 수 있습니다.
var target = event.target || event.srcElement;
var id = target.id
event.target
실패한 곳 event.srcElement
은 IE 를 위해 폴백됩니다. 위의 코드를 명확히하기 위해 jQuery는 필요하지 않지만 jQuery에서도 작동합니다.
(this)
함수를 실행 한 개체를 참조하는 데 사용할 수 있습니다 .
'this'
A는 DOM의 는 방법 (jQuery를 컨텍스트에서), 예를 들면, 클릭에 의해 호출되는 각각 결합 등 콜백 함수의 내부에있을 때 소자.
Here is where you can learn more: http://remysharp.com/2007/04/12/jquerys-this-demystified/
I generate a table dynamically out a database, receive the data in JSON and put it into a table. Every table row got a unique ID
, which is needed for further actions, so, if the DOM is altered you need a different approach:
$("table").delegate("tr", "click", function() {
var id=$(this).attr('id');
alert("ID:"+id);
});
Element which fired event we have in event property
event.currentTarget
We get DOM node object on which was set event handler.
Most nested node which started bubbling process we have in
event.target
Event object is always first attribute of event handler, example:
document.querySelector("someSelector").addEventListener(function(event){
console.log(event.target);
console.log(event.currentTarget);
});
More about event delegation You can read in http://maciejsikora.com/standard-events-vs-event-delegation/
The source element as a jQuery object should be obtained via
var $el = $(event.target);
This gets you the source of the click, rather than the element that the click function was assigned too. Can be useful when the click event is on a parent object EG.a click event on a table row, and you need the cell that was clicked
$("tr").click(function(event){
var $td = $(event.target);
});
You can try to use:
$('*').live('click', function() {
console.log(this.id);
return false;
});
In the case of delegated event handlers, where you might have something like this:
<ul>
<li data-id="1">
<span>Item 1</span>
</li>
<li data-id="2">
<span>Item 2</span>
</li>
<li data-id="3">
<span>Item 3</span>
</li>
<li data-id="4">
<span>Item 4</span>
</li>
<li data-id="5">
<span>Item 5</span>
</li>
</ul>
and your JS code like so:
$(document).ready(function() {
$('ul').on('click li', function(event) {
var $target = $(event.target),
itemId = $target.data('id');
//do something with itemId
});
});
You'll more than likely find that itemId is undefined
, as the content of the LI is wrapped in a <span>
, which means the <span>
will probably be the event target. You can get around this with a small check, like so:
$(document).ready(function() {
$('ul').on('click li', function(event) {
var $target = $(event.target).is('li') ? $(event.target) : $(event.target).closest('li'),
itemId = $target.data('id');
//do something with itemId
});
});
Or, if you prefer to maximize readability (and also avoid unnecessary repetition of jQuery wrapping calls):
$(document).ready(function() {
$('ul').on('click li', function(event) {
var $target = $(event.target),
itemId;
$target = $target.is('li') ? $target : $target.closest('li');
itemId = $target.data('id');
//do something with itemId
});
});
When using event delegation, the .is()
method is invaluable for verifying that your event target (among other things) is actually what you need it to be. Use .closest(selector)
to search up the DOM tree, and use .find(selector)
(generally coupled with .first()
, as in .find(selector).first()
) to search down it. You don't need to use .first()
when using .closest()
, as it only returns the first matching ancestor element, while .find()
returns all matching descendants.
This works on a higher z-index
than the event parameter mentioned in above answers:
$("#mydiv li").click(function(){
ClickedElement = this.id;
alert(ClickedElement);
});
This way you will always get the id
of the (in this example li
) element. Also when clicked on a child element of the parent..
Use can Use .on event
$("table").on("tr", "click", function() {
var id=$(this).attr('id');
alert("ID:"+id);
});
var buttons = document.getElementsByTagName('button');
var buttonsLength = buttons.length;
for (var i = 0; i < buttonsLength; i++){
buttons[i].addEventListener('click', clickResponse, false);
};
function clickResponse(){
// do something based on button selection here...
alert(this.id);
}
Working JSFiddle here.
this works with most types of elements:
$('selector').on('click',function(e){
log(e.currentTarget.id);
});
this.element.attr("id")
works fine in IE8.
Just use the this
reference
$(this).attr("id")
or
$(this).prop("id")
Both of these work,
jQuery(this).attr("id");
and
alert(this.id);
You can use the function to get the id and the value for the changed item(in my example, I've used a Select tag.
$('select').change(
function() {
var val = this.value;
var id = jQuery(this).attr("id");
console.log("value changed" + String(val)+String(id));
}
);
I'm working with
jQuery Autocomplete
I tried looking for an event
as described above, but when the request function fires it doesn't seem to be available. I used this.element.attr("id")
to get the element's ID instead, and it seems to work fine.
In case of Angular 7.x you can get the native element and its id or properties.
myClickHandler($event) {
this.selectedElement = <Element>$event.target;
console.log(this.selectedElement.id)
this.selectedElement.classList.remove('some-class');
}
html:
<div class="list-item" (click)="myClickHandler($event)">...</div>
$(".classobj").click(function(e){
console.log(e.currentTarget.id);
})
참고URL : https://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event
'code' 카테고리의 다른 글
C ++에서 POD 유형은 무엇입니까? (0) | 2020.09.28 |
---|---|
JDK (JNI 공유 라이브러리)를로드하지 못했습니다. (0) | 2020.09.28 |
Node.js를 사용하여 현재 스크립트의 경로를 어떻게 얻습니까? (0) | 2020.09.28 |
여러 열로 그룹화 (0) | 2020.09.28 |
Bootstrap 열을 모두 같은 높이로 만들려면 어떻게해야합니까? (0) | 2020.09.28 |