Методы attachEvent/addEventListener имеют ряд общих недостатков.
Во-первых, ни W3C ни Microsoft не определяют порядок срабатывания обработчиков. Несколько обработчиков одного события на элементе могут сработать в любом порядке.
На текущий момент (март 2010) addEventListener сохраняет порядок назначения обработчиков, а attachEvent в IE - нет.
elem.attachEvent("onclick", handler);
elem.attachEvent("onclick", handler2);
// может быть так, что handler2 сработает раньше handler.
// так, судя по демке ниже, ведет себя IE.
// а может быть, handler сработает раньше handler2.
// так в демо ниже ведет себя Opera
// ... вообще, порядок неопределен
Есть еще одна проблема, с которой можно столкнуться при управлении событиями: нельзя точно сказать установлен ли определённый обработчик, или нет, и какие обработчики установлены на данный момент.
В спецификации DOM 3 существует объект eventListenerList, но он слишком новый и на данный момент не поддерживается ни одним из браузеров.
Основной недостаток attachEvent заключается в том, что функция-обработчик не получает текущий элемент, на котором сработало событие, ни в каком виде.
Значение this указывает на window, а свойство event.currentTarget отсутствует.
И это достаточно важная особенность!
Например, пусть мы хотим подсвечивать divElem при клике.
Элемент divElem с разным текстом и различными ссылками, и даже с жирным текстом внутри тага <b>
Конечно, же мы повесим обработчик на divElem:
divElem.attachEvent("onclick", handler)
Но при клике из объекта события event в IE можно получить только srcElement, то есть самый глубокий кликнутый элемент. Он может быть ссылкой <a> или элементом <b>, но нам-то нужны не они, а сам divElem, чтобы его подсветить.
Обработчик, добавленный при помощи attachEvent никак не может выяснить объект, на который подвешен.
Впрочем, это легко обойти при помощи небольшого замыкания, корректно передающего указатель this:
Но этот код порождает утечку памяти в Internet Explorer 6, на который не установлено исправляющее обновление, вышедшее в июне 2007 года, из-за круговой ссылки DOM <-> JS.
Можно повесить несколько обработчиков на одно событие
Вот я только одного не могу понять:
какой толк в attachEvent и addEventListener, если все всеравно все они выполняются по одному событию? Ну напишу я 10 раз attachEvent, перечислив 10 разных функций. И что? Где это пригодится на практике? Проще объявить onclick, адрес функции и в ней уже перечислить список тех 10 функций. Разве так не проще?
На практике одно и тоже. Я не вижу ВООБЩЕ никаких плючов у attachEvent, за исключением примера с iframe
разовый обработчик не всегда есть возможность написать. Ибо элемент может не существовать, а появляться в результете каких-либо действий пользователя. Тут и поможет создание такого обработчика.
Исходники страниц браузер делает сам, поэтому не верь ему.
Если на сайте при входе будет работать сценарий, который выводит "Привет (Ваш ник(Допустим proVIDec))!", то при просмотре исходного кода браузер даст не php скрипт, а текст "Превет proVIDec".
Этот параметр объяснялся в главе введение в события:
Установка по стандарту W3C
Решение W3C работает во всех современных браузерах, кроме Internet Explorer.
Установка обработчика:element.addEventListener( имя_события, обработчик, фаза)
Удаление обработчика:element.removeEventListener( имя_события, обработчик, фаза)
Еще одно отличие от решения Microsoft это третий параметр – фаза.
Если он установлен в true, то при срабатывании события во вложенном элементе, обработчик будет вызван на фазе "перехвата", а если значение будет false, то - на фазе "всплывания". Подробнее об этом будет написано далее, в разделе этой статьи "Порядок срабатывания событий".
Немного дополню данный пост. Зачастую в функцию требуется передать некоторые параметры. Как вариант, можно расплодить глобальные переменные или создать один глобальный массив, из которого и вытягивать нужные значения. А можно решить данный вопрос и другим способом. Приведу свою функцию:
В данной функции генерится код двух других функций с подстановкой значений необходимых параметров в текстовом виде, после чего он прогоняется через eval - в результате мы имеем две функции select_region и select_city со всеми параметрами, которые им требовалось передать.
Придётся делать свой луна-парк.. Всем одна функция, в функции лист обработчиков. В принципе если сесть и подумать то легко, только как не дать убить никогда свой универсальный on<событие>?
Впрочем, это легко обойти при помощи небольшого замыкания, корректно передающего указатель this:
divElem.attachEvent("onclick", function() { handler.call(divElem) })
Вот только не всегда знаешь, какой это "divElem". А если есть список элементов, на который надо циклом назначить один обработчик, то здесь ваше решение не поможет.
Как правильно добавить обработчик (и вожможно ли такое) так чтоб при нажатии кнопки "Дальше" На сервер отправлялась информация не раз, а три раза с интервалом в одну секунду (с задержкой)!
Stan Smith’s are like the Air Jordans of Adidas. They look so iconic to look at. When you look at them out in public, you would instantly recognize that it was a Stan Smith shoe. That kind of recognition is very rare to find these days. Nothing ever really stands out, as everyone just copies everyone else just to ride a fad or a trend so that they can make a quick buck. Unlike the old days where people would compete who would wow the crowd more and who would grab the attention of the consumers. Back then, it was like roblox on pc where you would be transported to different worlds fashion. And every among us pc was valued for what it truly was.
Thanks for sharing this information. I am facing the same problem and I am very happy to be here! Glad you shared this topic for everyone to discuss. coloring pages
Why am I just now reading your latest post? Obviously, I selected the option to follow you. However, you do not use as many components in this article as you have in earlier articles. If you're feeling stressed, try playing basketball stars It's a game I like to play to unwind, and I hope it may help you as well.
wordle is a word cloud generator that lets you create a word cloud from any text. The tool has been around for years and has been used by thousands of people.
Wordle is a great tool for brainstorming or just to get your creative juices flowing. It's also great for presentations, as it provides an easy way to show off your knowledge or to share information with your audience in an engaging way.
You should also join fnaf world, the best horror game out there!
Возможно ли (и как правильно добавить обработчик), чтобы данные передавались на сервер не один раз, а три раза с задержкой в одну секунду между каждой отправкой mario games?
In any case, I appreciate your contribution. The way you wrote about the issue piqued my curiosity. Quite a few other individuals, I'm sure, share my enthusiasm for them. I was wondering how long it would take to write this piece. I've tried reading some other blogs, but I found them too difficult to follow. I really appreciate you providing such informative content for free. geometry dash
Although I am not knowledgeable heardle game about this topic, but through your article I have gained some useful information for myself. It is very effective for my work.
Pour trouver votre adresse IP, vous pouvez suivre ces étapes :
Sur un ordinateur Windows :
Ouvrez le menu Démarrer.
Recherchez et ouvrez l'application "Invite de commandes" ou "cmd".
Dans la fenêtre de l'invite de commandes, tapez "ipconfig" puis appuyez sur Entrée.
Vous verrez une liste d'informations réseau. Recherchez la ligne qui indique "Adresse IPv4" ou "IPv4 Address". À côté de cette ligne, vous trouverez votre adresse IP.
Sur un ordinateur Mac :
Cliquez sur l'icône Apple dans le coin supérieur gauche de l'écran.
Sélectionnez "Préférences Système".
Choisissez "Réseau".
Dans la colonne de gauche, sélectionnez votre connexion réseau active (Wi-Fi ou Ethernet).
Vous verrez votre adresse IP affichée à droite, à côté de "Adresse IP".
Sur un smartphone ou une tablette (iOS ou Android) :
Ouvrez les paramètres de votre appareil.
Recherchez l'option "Wi-Fi" ou "Réseau" et appuyez dessus.
Trouvez le réseau Wi-Fi auquel vous êtes connecté et appuyez sur le "i" ou l'icône d'information à côté de ce réseau.
Vous verrez votre adresse IP répertoriée sous "Adresse IP" ou "IP Address".
Gardez à l'esprit que votre adresse IP peut changer en fonction de votre connexion et du réseau auquel vous êtes connecté.
Please accept my heartfelt thanks for the author's meticulous fnaf attention to detail, ensuring the accuracy and reliability of the information presented, and establishing this article as a trustworthy source for knowledge and understanding.
Your blog gives me a lot of particularly good inspiration. I think more and more people will see your blog because you write really well. I hope your blog will be seen and liked by more people.https://totowho.com
It's really a very literary post.I feel your happiness and positive attitude towards life from your blog. What I want to tell you is that I learned a lot from your excellent writing skills. I will study harder like you.I want to write my opinion based on your writing.https://totowho.com
You're really a good hand, you write clear thinking, deep feelings, more people will feel your sincerity because you're good enough, your posts are sharing seriously, that's why you're successful, you're convincing, hope you keep your enthusiasm, I'll learn everything you say.https://totowho.com
There's no doubt about it It's fantastic All these smaller facts are made using digital and credential techniques I actually like the best value of reasoning.토토사이트
I get a lot of great ideas from your blog. Because of how wonderfully you write, I predict that more and more people will visit your blog. I really hope more people read and enjoy your blog. coreball
Thank you for producing such a fascinating essay on this subject pizza tower. This has sparked a lot of thought in me, and I'm looking forward to reading more.
Вопросы по прочитанному. Именно по прочитанному, чтобы ответ на него помог другим разобраться в предмете статьи. Другие вопросы могут быть удалены. Для остальных вопросов и обсуждений есть форум.
P.S. Лучшее "спасибо" - не комментарий, как все здорово, а рекомендация или ссылка на статью.
Вот я только одного не могу понять:
какой толк в attachEvent и addEventListener, если все всеравно все они выполняются по одному событию? Ну напишу я 10 раз attachEvent, перечислив 10 разных функций. И что? Где это пригодится на практике? Проще объявить onclick, адрес функции и в ней уже перечислить список тех 10 функций. Разве так не проще?
На практике одно и тоже. Я не вижу ВООБЩЕ никаких плючов у attachEvent, за исключением примера с iframe
Скачал ты чей-то скрипт, а он ставит обработчик через elem.on(событие). И убил все твои обработчики на это событие.
разовый обработчик не всегда есть возможность написать. Ибо элемент может не существовать, а появляться в результете каких-либо действий пользователя. Тут и поможет создание такого обработчика.
И в правду, зачем вешать onclick'и через addEventListener и attachEvent, эсли
можно сделать проще:
И тем более, attachEvent нестабильно работает в Опере и IE.
If I push the button once, can I submit the form twice? happy wheels
у меня по кнопке addEventListener выдаются алерты с 1 по 7 на FF.
это чей-то глюк или опечатка?
Видимо это можно отнести к недостутку этого способа - когда алертишь 5 раз он алертится 7 раз :-))))
ps: если открыть исходник страницы, то можно увидить
Исходники страниц браузер делает сам, поэтому не верь ему.
Если на сайте при входе будет работать сценарий, который выводит "Привет (Ваш ник(Допустим proVIDec))!", то при просмотре исходного кода браузер даст не php скрипт, а текст "Превет proVIDec".
Браузер ничего с исходниками страниц не делает. Он рендерит то, что отдаст сервер.
А обработкой php скриптов (как и любых других server-side'овых) как раз занимается сервер.
Впрочем, это легко обойти при помощи небольшого замыкания, корректно передающего указатель this:
А вот так
передать получится?
Третий параметр в addEventListener совсем не понятен
Что за "фаза погружения"?
Этот параметр объяснялся в главе введение в события:
Установка по стандарту W3C
Решение W3C работает во всех современных браузерах, кроме Internet Explorer.
Установка обработчика:element.addEventListener( имя_события, обработчик, фаза)
Удаление обработчика:element.removeEventListener( имя_события, обработчик, фаза)
Еще одно отличие от решения Microsoft это третий параметр – фаза.
Если он установлен в true, то при срабатывании события во вложенном элементе, обработчик будет вызван на фазе "перехвата", а если значение будет false, то - на фазе "всплывания". Подробнее об этом будет написано далее, в разделе этой статьи "Порядок срабатывания событий".
Немного дополню данный пост. Зачастую в функцию требуется передать некоторые параметры. Как вариант, можно расплодить глобальные переменные или создать один глобальный массив, из которого и вытягивать нужные значения. А можно решить данный вопрос и другим способом. Приведу свою функцию:
В данной функции генерится код двух других функций с подстановкой значений необходимых параметров в текстовом виде, после чего он прогоняется через eval - в результате мы имеем две функции select_region и select_city со всеми параметрами, которые им требовалось передать.
Плохое решение. Лучше сделать это с использованием замыкания.
Придётся делать свой луна-парк.. Всем одна функция, в функции лист обработчиков. В принципе если сесть и подумать то легко, только как не дать убить никогда свой универсальный on<событие>?
Вот только не всегда знаешь, какой это "divElem". А если есть список элементов, на который надо циклом назначить один обработчик, то здесь ваше решение не поможет.
Где можно найти имена всех событий?
i am not sure...fencing pensacola fl
Узнал про Greasemonkey. Тренируюсь. Почему-то нижеследующий скрипт работает практически всюду, кроме "e.mail.ru", подскажите почему?
window.addEventListener('load',function(e){
alert('alert [10-33-12]');
},true);
"Особенности addEventListener
Решение W3C работает во всех современных браузерах, кроме Internet Explorer."
Работает в IE 9 >
Только что проверил в IE 11 - все ок
Подскажите пожалуста кто нибуть!
Имеем опредиленый код формы:
Как правильно добавить обработчик (и вожможно ли такое) так чтоб при нажатии кнопки "Дальше" На сервер отправлялась информация не раз, а три раза с интервалом в одну секунду (с задержкой)!
Или скажу по проще:
Можна продублировать как-то отправку формы, от нажатия только одногораза на кнопку!?
Вот это то, что надо!
Большой! Объясните подробно и по существу, могу я поделиться вашей статьей? Многим будет полезно прочитать эту вашу статью. cookie clicker
Stan Smith’s are like the Air Jordans of Adidas. They look so iconic to look at. When you look at them out in public, you would instantly recognize that it was a Stan Smith shoe. That kind of recognition is very rare to find these days. Nothing ever really stands out, as everyone just copies everyone else just to ride a fad or a trend so that they can make a quick buck. Unlike the old days where people would compete who would wow the crowd more and who would grab the attention of the consumers. Back then, it was like roblox on pc where you would be transported to different worlds fashion. And every among us pc was valued for what it truly was.
Thanks for sharing this information. I am facing the same problem and I am very happy to be here! Glad you shared this topic for everyone to discuss.
coloring pages
Why am I just now reading your latest post? Obviously, I selected the option to follow you. However, you do not use as many components in this article as you have in earlier articles. If you're feeling stressed, try playing basketball stars It's a game I like to play to unwind, and I hope it may help you as well.
wordle is a word cloud generator that lets you create a word cloud from any text. The tool has been around for years and has been used by thousands of people.
Wordle is a great tool for brainstorming or just to get your creative juices flowing. It's also great for presentations, as it provides an easy way to show off your knowledge or to share information with your audience in an engaging way.
You should also join fnaf world, the best horror game out there!
I am grateful basket random for the information and the suggestions that you have provided. I will make an effort to understand it better for more.
Many internet games are amusing. I often play stumble guys, a knockout game to test boys' brains.
Возможно ли (и как правильно добавить обработчик), чтобы данные передавались на сервер не один раз, а три раза с задержкой в одну секунду между каждой отправкой mario games?
In any case, I appreciate your contribution. The way you wrote about the issue piqued my curiosity. Quite a few other individuals, I'm sure, share my enthusiasm for them. I was wondering how long it would take to write this piece. I've tried reading some other blogs, but I found them too difficult to follow. I really appreciate you providing such informative content for free. geometry dash
This is so amazing, great minds think alike I just wrote a similar post on this topic! You should check it out. basketball legends
It's great that I read your post, the information you share is new and very useful to me. wordle
I like your article, it helps me understand more things I don't know apk mod.
Thank you for sharing this amazing Blog fouad whatsapp download
you can explore the new and unique things on the shadow fight arena pc
and also check the basketball hoop for driveway
I'm glad I read your article since the knowledge you provide is fresh and helpful to me. 1v1 lol
The way you framed the drift hunters topic was unique and made me see it in a new light.
Although I am not knowledgeable heardle game about this topic, but through your article I have gained some useful information for myself. It is very effective for my work.
Your article is really squidward awesome. Thank you for bringing such a useful article to everyone
Si tu cherches un plan cul regarde par ici !
this is an informative post and it is very beneficial and knowledgeable. free games
Pour trouver votre adresse IP, vous pouvez suivre ces étapes :
Sur un ordinateur Windows :
Ouvrez le menu Démarrer.
Recherchez et ouvrez l'application "Invite de commandes" ou "cmd".
Dans la fenêtre de l'invite de commandes, tapez "ipconfig" puis appuyez sur Entrée.
Vous verrez une liste d'informations réseau. Recherchez la ligne qui indique "Adresse IPv4" ou "IPv4 Address". À côté de cette ligne, vous trouverez votre adresse IP.
Sur un ordinateur Mac :
Cliquez sur l'icône Apple dans le coin supérieur gauche de l'écran.
Sélectionnez "Préférences Système".
Choisissez "Réseau".
Dans la colonne de gauche, sélectionnez votre connexion réseau active (Wi-Fi ou Ethernet).
Vous verrez votre adresse IP affichée à droite, à côté de "Adresse IP".
Sur un smartphone ou une tablette (iOS ou Android) :
Ouvrez les paramètres de votre appareil.
Recherchez l'option "Wi-Fi" ou "Réseau" et appuyez dessus.
Trouvez le réseau Wi-Fi auquel vous êtes connecté et appuyez sur le "i" ou l'icône d'information à côté de ce réseau.
Vous verrez votre adresse IP répertoriée sous "Adresse IP" ou "IP Address".
Gardez à l'esprit que votre adresse IP peut changer en fonction de votre connexion et du réseau auquel vous êtes connecté.
Please accept my heartfelt thanks for the author's meticulous fnaf attention to detail, ensuring the accuracy and reliability of the information presented, and establishing this article as a trustworthy source for knowledge and understanding.
Your blog gives me a lot of particularly good inspiration. I think more and more people will see your blog because you write really well. I hope your blog will be seen and liked by more people.https://totowho.com
It's really a very literary post.I feel your happiness and positive attitude towards life from your blog. What I want to tell you is that I learned a lot from your excellent writing skills. I will study harder like you.I want to write my opinion based on your writing.https://totowho.com
You're really a good hand, you write clear thinking, deep feelings, more people will feel your sincerity because you're good enough, your posts are sharing seriously, that's why you're successful, you're convincing, hope you keep your enthusiasm, I'll learn everything you say.https://totowho.com
Thank you very much for this article. This information is really helpful to me tunnel rush
Can I share it? geometry dash
Great contribution! Also for the Snus bestellen a javascript is used as far as I know.
There's no doubt about it It's fantastic All these smaller facts are made using digital and credential techniques I actually like the best value of reasoning.토토사이트
I get a lot of great ideas from your blog. Because of how wonderfully you write, I predict that more and more people will visit your blog. I really hope more people read and enjoy your blog. coreball
Great blog! Can you explain me more?
Thank you very much for the useful information that the blogs have shared Pizza Tower.
this is an informative post and it is very beneficial and knowledgeable. gorilla tag
I feel it is well worth spending a few fnf minutes reading the useful information you provide. I appreciate it.
I can't thank the author heardle 60s enough for bringing this crucial topic to the forefront of our minds. Exceptional work!
Thank you for producing such a fascinating essay on this subject pizza tower. This has sparked a lot of thought in me, and I'm looking forward to reading more.
Dinosaur games have become a bonding activity for our family. We play together and have a blast.
This article provides us with the light to observe reality. We really appreciate your blog post. After visiting your post you will find many ways.먹튀검증
This is the special method applied for tap tap shots
Отправить комментарий
Приветствуются комментарии:Для остальных вопросов и обсуждений есть форум.