简体   繁体   English

ul li $(this).text()不显示任何内容

[英]ul li $(this).text() shows nothing

SOLVED! 解决了! actually the problem was in $(document).ready(function(){//}); 实际上问题出在$(document).ready(function(){//})中; after i used it, it worked fine. 我使用它后,它工作正常。 thanks for your help and sorry because of such silly mistake. 谢谢您的帮助,由于这种愚蠢的错误,我们深表歉意。

I'm trying to get selected li from bootstrap dropdown menu. 我正在尝试从引导下拉菜单中选择li。 It works but when i want to get the text of selected li, it shows nothing. 它有效,但是当我想获取所选li的文本时,它什么也没显示。

<div class="btn-group">
    <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
        <font id="dropdownMenu" >inch</font>
        <span class="caret"></span>
    </a>
    <ul id="dropdownList" class="dropdown-menu">
        <li><a href="#">inch</a></li>
        <li><a href="#">cm</a></li>
        <li><a href="#">mm</a></li>
    </ul>
</div>

js: JS:

$('#dropdownList li').click(function () {
    console.log($(this).text());
    document.getElementById('dropdownMenu').innerHTML = $(this).text();
});

May i know why it's not working? 我可以知道为什么它不起作用吗?

Thanks! 谢谢!

Get the text of an anchor tag inside. 获取内部锚标签的文本。 That's the element with text. 这就是带有文本的元素。

$('#dropdownList li').click(function () {
    console.log($(this).find('a').text());
    document.getElementById('dropdownMenu').innerHTML = $(this).find('a').text();
});

Use Jquery: 使用Jquery:

JSFiddle 的jsfiddle

$('#dropdownList li').click(function () {
    console.log($(this).text());
    $('#dropdownMenu').text($(this).text());
});

You should try to limit DOM reading/writing, like using .find() and the .text() etc. I would add some data in the markup 您应该尝试限制DOM的读/写,例如使用.find().text()等。我会在标记中添加一些数据

HTML: HTML:

<ul id="dropdownList" class="dropdown-menu">
  <li data-value="inch"><a href="#">inch</a></li>
  <li data-value="cm"><a href="#">cm</a></li>
  <li data-value="mm"><a href="#">mm</a></li>
</ul>

JS: JS:

$('#dropdownList li').click(function () {
  console.log($(this).data('value'))
})

Working Demo 工作演示

Two things: 两件事情:

  • The data-* are valid HTML5 tags that you can use to fit your needs. data-*是有效的HTML5标记,可用于满足需要。
  • Don't re-read the DOM for each clicks var dropdownValue = $('#value') . 不要为每次点击重新读取DOM var dropdownValue = $('#value')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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