jQuery获取<li>标签内的文本

26

我有这个


<div class="RestauranstSection">
    <label>
        Restaurant:
    </label>
    <input type="text"/>
    <input type="button" value="Search"/>
    <ul>
        <?php while ($row = $restaurants->fetch()) {
            ?>
            <li id="<?php echo $row['ID']; ?>">
                <?php echo $row['name']; ?>
            </li>
        <?php } ?>
    </ul>
</div>

我希望当点击任何一个li元素时,能够弹出该元素的文本内容。

$(".RestauranstSection").on('click','li',function (){});
怎么做呢?

1
你有没有阅读过 http://api.jquery.com/text/? - Frédéric Hamidi
1
@FrédéricHamidi 我没有。 - Marco Dinatsoli
1
我不想成为“那个人”,但是说真的,搜索jquery获取元素文本会将http://api.jquery.com/text/作为第一个结果呈现,同时还有其他相关的SO问题。 - Felix Kling
4个回答

59
$(".RestauranstSection").on('click','li',function (){
    alert($(this).text());
});

非常感谢,我会接受您的答案,在10分钟后。 - Marco Dinatsoli

5
您只需要选择li并像这样注册点击事件:
$(".RestauranstSection li").click(function (){
    alert($(this).text());
});

你可能也想拼写检查RestaurantsSection ;)


3

尝试

$(".RestauranstSection").on('click','li',function (){
    alert($(this).html())
});

演示: Fiddle

1
@MarcoDinatsoli:作为参考,html()会显示HTML标记。如果您的列表是<li><strong>Hello</strong>, world!</li>,那么html()的结果将是"<strong>Hello</strong>, world!",而text()则是"Hello, world!" - James Donnelly

0

如果您正在使用ES2015箭头函数语法作为click回调,您可能想要使用$(e.currentTarget).text()

$(".RestauranstSection li").click((e)=>{ alert($(e.currentTarget).text()); });


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接