定位列表项但不是它的元素的javascript事件

时间:2018-01-05 14:26:47

标签: javascript events dynamic javascript-events event-handling

我有这个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>
&#13;
&#13;
&#13;

建议列表是根据输入动态更新的,并且我试图使用列表获取列表项textContent(如果它在那里)。
如果我按列表项,列表项内的范围或整个列表,则当前代码将获取整个列表内容,具体取决于您按下的位置。这些是来自更大文档的片段。

请不要jquery答案。

1 个答案:

答案 0 :(得分:0)

检查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>