使用 jquery 获取 ul 中每个 li 的 ID 或名称

Get Id or Name of each li in ul with jquery

本文关键字:ID li 获取 jquery ul 使用      更新时间:2023-09-26

我想使用 jquery 获取 ul 中每个 li 的 id 和文本名称

我试过这个,但没有用

<ul id="tags1">
    @foreach (var item in Model.Tags)
    {             
        <li id=@item.TagName >@item.TagName</li>    
    }    
</ul>

我已经尝试过这段代码,但它给了我很多或html

$('#tags1 li').each(function (i) {
    alert($(this).html());
    console.log($(this).html());
});

它给了我

<span class="tagit-label">Art</span><a class="tagit-close"><span class="text-icon">×</span><span class="ui-icon ui-icon-close"></span></a><input type="hidden" style="display:none;" value="Art" name="tags">

我只需要获取值值="艺术"

谢谢

你可以像下面这样做。

$('#tags1 li').each(function () {
    console.log(this.id);  //id
    console.log($('.tagit-label', this).text());  //text
});
$('#tags1 li').each(function () {
    console.log(this.id);
    console.log($(this).text());
});