使用jquery在ul菜单中添加li dynamic

Adding a li dynamik in a ul menu with jquery

本文关键字:添加 li dynamic 菜单 jquery ul 使用      更新时间:2023-09-26

我有一个jquery已经加载的菜单。我不想编辑加载这个菜单的当前js文件,所以我想用jquery在这个菜单的最后一个li的末尾添加一个额外的li。我的菜单结构是:

<div class="toolbar">
    <ul id="dcsns-filter" class="option-set filter">
        <li><a href="#filter" data-group="dc-filter" data-filter="*" class="selected link-all">all</a>
        </li>
    </ul>
</div>    

我尝试了下面的代码,但没有机会。。

<script>
$(document).ready(function () {
    var tsource = "http://www.google.com"
    $(".dcsns-toolbar").find("li:last").after("<div style='width:100px; height:61px; float: left; top:0; position: absolute; margin-top:140px; margin-right:5px;'><div style=' width:65px; height:61px; float:left;'>Πηγή: <a href='" + tsource + "' target='_blank' style='color:#fff; text-decoration:none; font-family:Verdana, Geneva, sans-serif; font-size:12px;'>Google</a></div></div>");
});
</script>

谢谢!!

我认为您的jQuery Selector:中有一个错误

$(".dcsns-toolbar")  // <--- This element doesn't exist

应该是

$('#dcsns-filter')

然后jQuery将找到您的元素,您可以将其附加到该元素中。

$('#dcsns-filter').find("li:last").after("<div style='width:100px; height:61px; float: left; top:0; position: absolute; margin-top:140px; margin-right:5px;'><div style=' width:65px; height:61px; float:left;'>Πηγή: <a href='" + tsource + "' target='_blank' style='color:#fff; text-decoration:none; font-family:Verdana, Geneva, sans-serif; font-size:12px;'>Google</a></div></div>");
var innerHtml = '<div>...</div>';
var newListItem = $('<li />').html(innerHtml);
$("#dcsns-filter").append(newListItem);
$("#dcsns-filter").append('Your new li html');