Какие свойства я могу использовать с событием.цель?



Мне нужно определить элементы, из которых событий.



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



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




  • href

  • id

  • nodeName


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



EDIT:



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

719   6  

6 ответов:

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

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

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

Если бы вы осмотрели событие.цель с помощью 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
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

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


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()`

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

Я пробовал с jQuery

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

возвращает ошибку :

.attr, который не работает

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

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

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

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

Comments

    Ничего не найдено.