javascript 努力添加一个模糊事件监听器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25271366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:16:39  来源:igfitidea点击:

Struggling to add a blur event listener

javascriptbluronblurgoogle-tag-managerdata-layers

提问by Doug Fir

I have a searchbox on the site I work on and would like to track the search terms folk are looking for.

我在我工作的网站上有一个搜索框,我想跟踪人们正在寻找的搜索词。

Since the searchbox auto guesses what someone is typing and searches for it, there is no click event.

由于搜索框会自动猜测某人正在键入的内容并进行搜索,因此没有单击事件。

In the console the textContent that I want when the blur happens is the .textContent of this:

在控制台中,发生模糊时我想要的 textContent 是以下内容的 .textContent:

myVar = document.querySelectorAll('.twitter-typeahead > span')[2]

But the value returned here is only not null when someone has actually typed something. So attaching a blur event seems the way to go. On the back of someones help on another forum I got this far in the console:

但是这里返回的值只有在有人实际输入内容时才不为空。所以附加一个模糊事件似乎是要走的路。在另一个论坛上有人帮助的背后,我在控制台中做到了这一点:

myVar.addEventListener('blur', function(){dataLayer.push({'event':'bla'})})

After typing this all in the console I don't see any values being pushed to the dataLayer which makes me think that the blur event is not working (as opposed to the dataLayer.push function.)

在控制台中键入所有内容后,我没有看到任何值被推送到 dataLayer,这让我认为模糊事件不起作用(与 dataLayer.push 函数相反。)

The page with the searchbox in question is here.

带有相关搜索框的页面在这里

How would I attach a blur event to someone unfocussing the search box?

我如何将模糊事件附加到未聚焦搜索框的人?

回答by Barmar

You should add the blurlistener to the search box, not a span:

您应该将blur侦听器添加到搜索框,而不是跨度:

searchbox = document.getElementById('searchboxID');
searchbox.addEventListener('blur', function() {
    var input = this.value;
    // Do whatever you want with the input
});

回答by leonheess

ES6 provides even shorter possibilities:

ES6 提供了更短的可能性:

let el = document.getElementById('id');
el.addEventListener('blur', () => console.log('blurred'));

Or if you need the element:

或者,如果您需要该元素:

let el = document.getElementById('id');
el.addEventListener('blur', (event) => console.log(event.target));

Snippet:

片段:

let el = document.getElementById('id');
el.addEventListener('blur', (event) => console.log(`${event.target}: ${event.target.value}`));
<input id="id" />