Get UL list content with jquery

二次信任 提交于 2019-12-24 12:45:29

问题


I need to get content from a UL list and then be able to use that to email. But I'm stuck on getting the ul list in jquery. I've searched and found the following:

$(document).ready(function(){
    $("#send").click(function() { //When trigger is clicked...
            var optionTexts = [];
            $("#thelist").each(function() { optionTexts.push($(this).text()) });
            var text = '"' + optionTexts.join('"<br/> "') + '"';

            $("#result").append(text);

        });
    });

but this returns all contents inside the page :S Here's my ul list:

<ul id="thelist">
  <li style="height: 65px; display: list-item; ">
    <ul>
      <li class="botHeader">
        "Evelin dice"
                <span>14:37:52</span>
      </li>
      <li class="botMsg">
        "Hola, bienvenido"
      </li>
    <ul>
  </li>
  <li style="height: 26px; display: list-item; ">
    <ul>
      <li class="userHeader">
        "Usted dice"
                <span>14:37:59</span>
      </li>
      <li class="userMsg">
        "Hola como estas"
      </li>
    <ul>
  </li>
  <li style="height: 39px; display: list-item; ">
    <ul>
      <li class="botHeader">
        "Evelin dice"
                <span>14:37:59</span>
      </li>
      <li class="botMsg">
        "Gracias por preguntar, todo bien"
      </li>
    <ul>
  </li>
</ul>

<a href="#" id="send">enviar</a>
<div id="result">

</div>

回答1:


This should do the whole lot in one go, and without any temporary variables:

$('#result').append(
    $('#thelist').find('li').filter(function() {
        return $(this).find('ul').length === 0;
    }).map(function(i, e) {
        return $(this).text();
    }).get().join('<br/>')
);

You have to only consider the <li> elements that don't have any <ul> descendents.

Working demo at http://jsfiddle.net/alnitak/JVS7d/




回答2:


First, you're markup is invalid. You're missing the closing </ul> on your inner lists. Second, you just need to add li to your selector for your $.each(...) function.

$(document).ready(function(){
    $("#send").click(function() { //When trigger is clicked...
        var optionTexts = [];
        $("#thelist li").each(function() { optionTexts.push($(this).text()) });
        var text = '"' + optionTexts.join('"<br/> "') + '"';

        $("#result").append(text);
    });
});   



回答3:


looks to me you should change the $("#thelist").each(function... to $("#thelist ul li").each(function...



来源:https://stackoverflow.com/questions/10761139/get-ul-list-content-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!