Подтвердить что ты не робот

Какие свойства можно использовать с event.target?

Мне нужно идентифицировать элементы, из которых запускаются события.

Использование event.target получает соответствующий элемент.

Какие свойства я могу использовать оттуда?

  • href
  • id
  • NODENAME

Я не могу найти много информации об этом, даже на страницах jQuery, поэтому нужно надеяться, что кто-то сможет завершить над списком.

EDIT:

Это может быть полезно: selfHTML node свойства и selfHTML HTML свойства

4b9b3361

Ответ 1

event.target возвращает элемент DOM, поэтому вы можете получить любое свойство/атрибут, который имеет значение; поэтому, чтобы более точно ответить на ваш вопрос, вы всегда сможете получить nodeName, и вы можете получить href и id, если у элемента есть href и id; в противном случае возвращается undefined.

Однако внутри обработчика событий вы можете использовать this, который также установлен на элемент DOM; намного проще.

$('foo').bind('click', function () {
    // inside here, `this` will refer to the foo that was clicked
});

Ответ 2

Если бы вы осмотрели event.target с помощью инструментов разработчика Firebug или Chrome, которые вы бы увидели для элемента span (например, следующие свойства), он будет иметь любые свойства, которые имеет любой элемент. Это зависит от того, что является целевым элементом:

event.target: HTMLSpanElement

attributes: NamedNodeMap
baseURI: "file:///C:/Test.html"
childElementCount: 0
childNodes: NodeList[1]
children: HTMLCollection[0]
classList: DOMTokenList
className: ""
clientHeight: 36
clientLeft: 1
clientTop: 1
clientWidth: 1443
contentEditable: "inherit"
dataset: DOMStringMap
dir: ""
draggable: false
firstChild: Text
firstElementChild: null
hidden: false
id: ""
innerHTML: "click"
innerText: "click"
isContentEditable: false
lang: ""
lastChild: Text
lastElementChild: null
localName: "span"
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: null
nextSibling: null
nodeName: "SPAN"
nodeType: 1
nodeValue: null
offsetHeight: 38
offsetLeft: 26
offsetParent: HTMLBodyElement
offsetTop: 62
offsetWidth: 1445
onabort: null
onbeforecopy: null
onbeforecut: null
onbeforepaste: null
onblur: null
onchange: null
onclick: null
oncontextmenu: null
oncopy: null
oncut: null
ondblclick: null
ondrag: null
ondragend: null
ondragenter: null
ondragleave: null
ondragover: null
ondragstart: null
ondrop: null
onerror: null
onfocus: null
oninput: null
oninvalid: null
onkeydown: null
onkeypress: null
onkeyup: null
onload: null
onmousedown: null
onmousemove: null
onmouseout: null
onmouseover: null
onmouseup: null
onmousewheel: null
onpaste: null
onreset: null
onscroll: null
onsearch: null
onselect: null
onselectstart: null
onsubmit: null
onwebkitfullscreenchange: null
outerHTML: "<span>click</span>"
outerText: "click"
ownerDocument: HTMLDocument
parentElement: HTMLElement
parentNode: HTMLElement
prefix: null
previousElementSibling: null
previousSibling: null
scrollHeight: 36
scrollLeft: 0
scrollTop: 0
scrollWidth: 1443
spellcheck: true
style: CSSStyleDeclaration
tabIndex: -1
tagName: "SPAN"
textContent: "click"
title: ""
webkitdropzone: ""
__proto__: HTMLSpanElement

Ответ 3

window.onclick = e => {
    console.dir(e.target);  // use this in chrome
    console.log(e.target);  // use this in firefox - click on tag name to view 
}  

enter image description here

воспользоваться преимуществами фильтра


e.target.tagName
e.target.className
e.target.style.height  // its not the value applied from the css style sheet, to get that values use 'getComputedStyle()'

Ответ 4

event.target возвращает узел, на который была нацелена функция. Это означает, что вы можете делать все, что захотите, с любым другим узлом, как тот, который вы получили бы из document.getElementById

Я пробовал с jQuery

var _target = e.target;
console.log(_target.attr('href'));

Вернуть ошибку:

.attr не работает

Но _target.attributes.href.value было работает.

Ответ 5

event.target возвращает node, на который была нацелена функция. Это означает, что вы можете делать все, что угодно, с любым другим node, подобным тому, который вы получили бы от document.getElementById

Ответ 6

Простой способ увидеть все свойства определенного узла DOM в Chrome (я нахожусь на v.69) - щелкнуть правой кнопкой мыши на элементе, выбрать проверку, а затем вместо просмотра вкладки "Стиль" нажать "Свойства".,

Внутри вкладки Свойства вы увидите все свойства вашего конкретного элемента.