简体   繁体   中英

Undefined text at click event on <li><p>text</p></li>

I'm trying to fix it... I really don't know why this is not working.

I have some <ul> where some <li> are inserted by keyUp/keydown events (tipical AJAX searcher) so, this <li> represents the DDBB matches now.

I would like to so some code after click in some <li> (this) and then get the text inside it (because I will use it to render another URL using this text as a parameter)... I don't know why I got undefined text 24/7.

Here is a demo : http://codepen.io/tureey/pen/VaagyY

 // Redirije a la URL pertinente para cargar la información de esa búsqueda $('#searcher-ajax li').click(function() { alert("enter"); var a = $(this).children('div').children('p').innerHTML; alert(a); }); 
 #searcher { margin-bottom: 0 !important; } #searcher-ajax { position: relative; top: 0; left: 0; right: 0; } #searcher-ajax li.searcher-ajax-element { color: white; list-style: none; border: 1px solid black; background: #040507 url("/static/img/bg-bar.jpg") repeat 50% 0; } #searcher-ajax li.searcher-ajax-element div { text-align: left; } #searcher-ajax li.searcher-ajax-element div img { width: 30px; height: 30px; max-width: 30px; max-height: 30px; margin: 0 1em; } #searcher-ajax li.searcher-ajax-element div p { display: inline-block; margin: 0 !important; } #searcher-ajax li.searcher-ajax-element:hover, #searcher-ajax li.searcher-ajax-element:active, #searcher-ajax li.searcher-ajax-element:focus { cursor: pointer; background: black; background-image: none; font-weight: bold; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script> <ul id="searcher-ajax"> <li class="searcher-ajax-element"> <div class="searcher-ajax-element-div"> <p>text1</p> </div> </li> <li class="searcher-ajax-element"> <div class="searcher-ajax-element-div"> <p>text2</p> </div> </li> <li class="searcher-ajax-element"> <div class="searcher-ajax-element-div"> <p>text3</p> </div> </li> </ul> 

Thanks for help.

You need to use jquery function find instead of children , because element you want to find ( p ) is not a direct child of your context ( li ).

Demo: http://codepen.io/anon/pen/VaagdL

How you could have fixed it sooner: do not presume your code works until the last step. You could have just checked and seen that $(this).children('p') already returns empty collection (not what you expected).

Your mistake is the path you are trying to find.

You need to do:

var a = $(this).children('div').children('p')[0].innerHTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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