簡體   English   中英

每個()的 jQuery 問題並為 ul 和 li 元素添加 function

[英]jQuery problem with each() and prepend function for ul and li elements

添加 JavaScript + jQuery 代碼,該代碼將在加載文檔后對列表項進行編號,方法是在開頭添加下一個粗體編號;

1 Poland
2 Germany
3 Italy

我的代碼如下:

<script type="text/javascript">
    $(function (){
        $('li').prepend(
            each(function(index){
                index++;
               index + ": " + $( this ).text();
            }))
        ;
    });
</script>
</head>

<body>
    <ul>
        <li>Poland</li>
        <li>Germany</li>
        <li>Italy</li>
    </ul>
</body>

不行。 我試了很多次都沒有結果。

如果我理解正確,您不需要為此使用 javascript。

請檢查下面,

 ul { counter-reset: my-awesome-counter; max-width: 350px; counter-reset: my-awesome-counter; list-style: none; padding-left: 40px; } ul li { margin: 0 0 0.5rem 0; counter-increment: my-awesome-counter; position: relative; } ul li:before { content: counter(my-awesome-counter); color: #fcd000; font-size: 1.5rem; font-weight: bold; position: absolute; left:-40px; line-height: 20px; width:30px; height:30px; top: 0; background: black; text-align: center; }
 <ul> <li>Poland</li> <li>Germany</li> <li>Italy</li> </ul>

如果您需要,還有更多信息;

https://css-tricks.com/custom-list-number-styling/

您可以ol in html (ordered list)或使用 javascript 或 jquery 來制作它,因為有時您可能不使用ol and ul Iul 來制作一個簡單的代碼表任何問題告訴我。

 // Using For Loop /*for (let i = 0; i < $("#ul li").length; i= i + 1 ) { $("#ul li").eq(i).prepend("<span class='counter'>" + (i + 1) + "</span> ") }*/ // Using Each Loop $( "#ul li" ).each(function( index ) { $(this).prepend("<span class='counter'>" + (index + 1) + "</span> ") });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="ul"> <li>Poland</li> <li>Germany</li> <li>Italy</li> </ul>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM