我有这个dom和JS:
var searchInput = document.getElementById('searchInp');
var suggestions = document.getElementById("suggest");
suggestions.addEventListener("click", function(evt) {
var pressed = evt.target.textContent;
searchInput.value = pressed;
}, false);
<input type="search" id="searchInp">
<ul id="suggest">
<li>example<span>something</span></li>
<li>test sentence</li>
<li><span>example</span> car</li>
</ul>
建议列表根据输入动态更新,如果存在,我正在尝试将列表项与跨度textContent
。如果我按列表项,
当前代码将获取整个列表内容,或列表项内的跨度,或整个列表,具体取决于您按下的位置。这些是来自较大文档的片段。
请不要j查询答案。
检查evt.target
它是否是 ul 元素本身,如果是,请忽略单击并执行return
。
否则检查它是否是 li 元素,如果不要使用 Element#closest(selector( 或 polyfill 沿着节点树向上移动,直到到达列表项
suggestions.addEventListener("click", function(evt) {
var listItem = null;
if (evt.target == suggestions) {
//they clicked somewhere on the UL itself and not a child element.
return;
} else if (!(evt.target instanceof HTMLLIElement)) {
//They clicked some other child element
//Find the closest parent list item that is direct child of #suggest
listItem = evt.target.closest('#suggest > li');
} else {
listItem = evt.target;
}
searchInput.value = listItem.textContent;
}, false);
演示
var searchInput = document.getElementById('searchInp');
var suggestions = document.getElementById("suggest");
suggestions.addEventListener("click", function(evt) {
var listItem = null;
if (evt.target == suggestions) {
return;
} else if (!(evt.target instanceof HTMLLIElement)) {
listItem = evt.target.closest('#suggest > li');
} else {
listItem = evt.target;
}
searchInput.value = listItem.textContent;
}, false);
<input type="search" id="searchInp">
<ul id="suggest">
<li>example<span>something</span></li>
<li>test sentence</li>
<li><span>example</span> car</li>
</ul>