簡體   English   中英

如何使用jquery一次只選擇一個LI元素?

[英]How to select only one LI element at time with jquery?

它的作用是從列表中選擇 LI 項目,但我希望它一次只能選擇一個。 例如,如果我單擊 Vaje 然后單擊 Projekt,則 Vaje 應該恢復正常等等,即使對於添加的用戶輸入也是如此。

 $(document).on('click', '.class', function(){ $(this).css("font-weight", 'bold'); $(this).css("text-decoration", 'underline'); $(document).ready(function(){ $("#add").click(function(){ var addItem= $("#dodaj").val(); if(addItem.length > 0){ $("ul").append('<li class="class">'+ addItem + '</li>'); $("#dodaj").val(""); } }); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id = "dodaj" name="additem"> <button id="add" onclick="newElement()">Dodaj</button> <button id="remove" >Zbriši</button> <ul id="kategorija" > <li class="class">Vaje</li> <li class="class">Treningi</li> <li class="class">Projekt</li> </ul>

單擊時,您正在為一個 li 設置“粗體”和“下划線”,但您沒有重置其他元素。 您可以將點擊事件更改為:

$(document).on('click', '.class', function(){ 
    // reset all li
    $('.class').css("font-weight", 'normal');
    $('.class').css("text-decoration", 'none');

    // now set the current li
    $(this).css("font-weight", 'bold'); 
    $(this).css("text-decoration", 'underline');
});

暫無
暫無

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

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