简体   繁体   English

使用 e.target 时不清除输入

[英]Input is not cleared when working with e.target

I can't figure out what's going on.我不知道发生了什么事。 Below is the JS code that is responsible for closing and opening the search box running in the JS application.下面是JS应用程序中运行的负责关闭和打开搜索框的JS代码。 Closing occurs by pressing a button with a cross, Esc keyboard and anywhere in this window通过按下带十字键的按钮、Esc 键盘和此 window 中的任何位置来关闭


const btn = document.querySelector('.head__search-icon'),
body = document.body,
search = document.querySelector('.search'),
searchInner = document.querySelector('.search__inner'),
searchOverlay = document.querySelector('.search__overlay'),
searchInput = document.querySelector('#search__input'),
btnClose = document.querySelector('.search__closed-button');
body.classList.add('no-search'),
search.style.display = 'none';


function searchOpen() {
btn.addEventListener('click', () => {
    body.classList.remove('no-search');
    body.classList.add('is-search');
    search.style.display = 'block';
    setTimeout(() => searchInput.focus(), 100);
    if (body.classList.contains('is-head-open')) {
        body.classList.remove('is-head-open');
    }
});
}
searchOpen();

function searchClose() {
    body.classList.add('no-search');
    body.classList.remove('is-search');
    searchInput.value = '';
    searchInput.blur();

}

function searchRemove(e) {
    if(e.code === "Escape" && body.classList.contains('is-search') || e.target === searchOverlay || e.target === searchInner) {
        searchClose();
    }
}

document.addEventListener('keydown', searchRemove);
search.addEventListener('click', searchRemove);
btnClose.addEventListener('click', searchClose);


The fact is that if there is a search result, and press Esc, then everything works, the focus from the input disappears, and the input itself is cleared.事实是,如果有搜索结果,然后按 Esc,那么一切正常,输入的焦点消失,输入本身被清除。 But if you click anywhere in the window ( e.target === searchOverlay || e.target === searchInner ), then the window itself closes, the input is cleared, as I need, except that with a visually clean input, the search results remain.但是,如果您单击 window 中的任意位置( e.target === searchOverlay || e.target === searchInner ),则 window 本身将关闭,输入将被清除,正如我所需要的,除了视觉上干净的输入,搜索结果仍然存在。 That is, you open the window again and see the same search results, although the input is empty.也就是说,您再次打开 window 并看到相同的搜索结果,尽管输入是空的。 When working with Esc, the input is actually cleared.使用 Esc 时,输入实际上被清除。 Where is the jamb in the script?脚本中的门框在哪里?

In general, I made it easier, added a construction to the searchClose() function to remove the search result using innerHTML = ' '总的来说,我让它变得更容易,在searchClose() function 中添加了一个结构来删除使用innerHTML = ' '的搜索结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM