如何从javascript

时间:2016-08-05 00:57:36

标签: javascript html

我试图从div元素中获取所选值,该元素使用下拉列表动态填充。这是在现有的网站上,所以我们使用额外的javascript将侦听器添加到div。请参阅附件代码示例。当我点击" red s"区域,我只得到部分HTML。理想情况下,我想要整个文本" red shoes"如果我点击" hoes"区域。如何获取单击的li元素的整个文本?

例如:



function getEventTarget(e) {
  e = e || window.event;
  return e.target || e.srcElement; 
}

var ul = document.getElementById('search_suggestion');
ul.onclick = function(event) {
  var target = getEventTarget(event);
  alert(target.innerHTML);
};

<div id="search_suggestion">
  <ul class="suggestion_keyword">
    <li><span class="keywords">red s</span>kirt
       <div class="brm-autosuggest-nub"></div></li>       
    <li><span class="keywords">red s</span>horts</li>
    <li><span class="keywords">red s</span>hoes</li>
    <li><span class="keywords">red s</span>hirt</li>            
  </ul>
</div>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

使用jquery编辑

&#13;
&#13;
$('li').on('click',function() {
  alert($(this).text());
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="search_suggestion">
  <ul class="suggestion_keyword">
    <li><span class="keywords">red s</span>kirt<div class="brm-autosuggest-nub"></div></li>       <li><span class="keywords">red s</span>horts</li>
    <li><span class="keywords">red s</span>hoes</li>
    <li><span class="keywords">red s</span>hirt</li>            
  </ul>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

问题的两个部分:首先,我看到点击事件的目标是跨度,而不是li。其次,正如其他人所指出的那样,你有文字和HTML混合在一起。您需要全文内容,不包括标记。 innerText或textContent都可以工作 - textContent会保留换行符。这是一个工作片段。

&#13;
&#13;
function getEventTarget(e) {
  e = e || window.event;
  return e.target || e.srcElement; 
}

var ul = document.getElementById('search_suggestion');
ul.onclick = function(event) {
  var target = getEventTarget(event);
  if(target.tagName === 'SPAN')
    target = target.parentNode;
  alert(target.textContent);
};
&#13;
<div id="search_suggestion">
  <ul class="suggestion_keyword">
    <li><span class="keywords">red s</span>kirt<div class="brm-autosuggest-nub"></div></li>       <li><span class="keywords">red s</span>horts</li>
    <li><span class="keywords">red s</span>hoes</li>
    <li><span class="keywords">red s</span>hirt</li>            
  </ul>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

而不是innerHTML,请尝试使用textContent

ul.onclick = function(event) {
  var target = getEventTarget(event);
  alert(target.textContent);
};

答案 3 :(得分:0)

您可以尝试使用innerText代替innerHTML

ul.onclick = function(event) {
  var target = getEventTarget(event);
  alert(target.innerText);
};