简体   繁体   English

我怎样才能使这个 JavaScript 代码更清洁?

[英]How can I can make this JavaScript code cleaner?

I'm new to JS and I did this exercise for the course I'm taking.我是 JS 的新手,我为我正在学习的课程做了这个练习。 It's basically done, but I had to repeat the code that creates the "delete" button and I'm not sure how I can make this cleaner.它基本上完成了,但我不得不重复创建“删除”按钮的代码,我不知道如何让这个更干净。

 var button = document.getElementById("add") var input = document.getElementById("userinput") var ul = document.querySelector("ul") var li = document.querySelectorAll("li") function inputLength() { return input.value.length; } function createListElement() { let li = document.createElement("li") li.appendChild(document.createTextNode(input.value)) ul.appendChild(li) input.value = "" // Create a delete button and configure it: var btnDelete = document.createElement("button"); btnDelete.classList.add("delete"); btnDelete.textContent = "Delete"; // Append the button to the list item li.appendChild(btnDelete); } // Create a delete button for each <li> already in the HTML file li.forEach(function(item){ var btnDelete = document.createElement("button"); btnDelete.classList.add("delete"); btnDelete.textContent = "Delete"; item.appendChild(btnDelete); }); function addListAfterClick() { if(inputLength() > 0) { createListElement() } } function addListAfterKeypress(event) { if(inputLength() > 0 && event.keyCode === 13) { createListElement() } } button.addEventListener("click", addListAfterClick) input.addEventListener("keypress", addListAfterKeypress) function toggleClassDoneOnAndOff(event) { if (event.target.tagName === "LI") { event.target.classList.toggle("done"); } } ul.addEventListener("click", toggleClassDoneOnAndOff); function deleteAfterClick(event) { // Determine if it was a delete button that was clicked if(event.target.classList.contains("delete")){ // Remove the closest li ancestor to the clicked element event.target.closest("li").remove(); } } // Handle all the clicks that originate from within the <ul> at // the <ul> level when they bubble up to it instead of setting each // button within the <ul> up with its own click event handler. ul.addEventListener("click", deleteAfterClick);
 .done { text-decoration: line-through; }
 <body> <h1>Shopping List</h1> <p id="first">Get it done today</p> <input id="userinput" type="text" placeholder="Add items"> <button id="add">Add</button> <ul id="ul"> <li>Notebook</li> <li>Jello</li> <li>Spinach</li> <li>Rice</li> <li>Birthday Cake</li> <li>Candles</li> </ul> <script type="text/javascript" src="script.js"></script> </body>

My question is that simple, but since Stack Overflow is telling me to "add some more details"...我的问题就是这么简单,但是由于 Stack Overflow 告诉我“添加更多细节”......

Basically, I tried to turn this part into a function:基本上,我试图把这部分变成 function:

var btnDelete = document.createElement("button");
btnDelete.classList.add("delete");
btnDelete.textContent = "Delete";

But I couldn't figure out how to make it work inside the other ones.但我不知道如何让它在其他的内部工作。

You'll just extract those 3 lines into their own function and have that function return the newly created element.您只需将这 3 行提取到它们自己的 function 中,并让 function 返回新创建的元素。 Where the lines are now will get replaced by the function call.现在这些行将被 function 调用替换。

 var button = document.getElementById("add") var input = document.getElementById("userinput") var ul = document.querySelector("ul") var li = document.querySelectorAll("li") function inputLength() { return input.value.length; } function createDelete(){ // Create a delete button and configure it: var btnDelete = document.createElement("button"); btnDelete.classList.add("delete"); btnDelete.textContent = "Delete"; return btnDelete; // <-- send the new element back to the function caller } function createListElement() { let li = document.createElement("li") li.appendChild(document.createTextNode(input.value)) ul.appendChild(li) input.value = "" // Append the button to the list item // The createDelete() function will be called first // and its return value (the new button) is what will // be appended. li.appendChild(createDelete()); } // Create a delete button for each <li> already in the HTML file li.forEach(function(item){ // The createDelete() function will be called first // and its return value (the new button) is what will // be appended. item.appendChild(createDelete()); }); function addListAfterClick() { if(inputLength() > 0) { createListElement() } } function addListAfterKeypress(event) { if(inputLength() > 0 && event.keyCode === 13) { createListElement() } } button.addEventListener("click", addListAfterClick) input.addEventListener("keypress", addListAfterKeypress) function toggleClassDoneOnAndOff(event) { if (event.target.tagName === "LI") { event.target.classList.toggle("done"); } } ul.addEventListener("click", toggleClassDoneOnAndOff); function deleteAfterClick(event) { // Determine if it was a delete button that was clicked if(event.target.classList.contains("delete")){ // Remove the closest li ancestor to the clicked element event.target.closest("li").remove(); } } // Handle all the clicks that originate from within the <ul> at // the <ul> level when they bubble up to it instead of setting each // button within the <ul> up with its own click event handler. ul.addEventListener("click", deleteAfterClick);
 .done { text-decoration: line-through; }
 <body> <h1>Shopping List</h1> <p id="first">Get it done today</p> <input id="userinput" type="text" placeholder="Add items"> <button id="add">Add</button> <ul id="ul"> <li>Notebook</li> <li>Jello</li> <li>Spinach</li> <li>Rice</li> <li>Birthday Cake</li> <li>Candles</li> </ul> <script type="text/javascript" src="script.js"></script> </body>

you can create this function,你可以创建这个 function,

 function createBtnDelete(btn) {
        const btnDelete = document.createElement("button");
        btnDelete.classList.add("delete");
        btnDelete.textContent = "Delete";
        btn.appendChild(btnDelete);
    }

and use li.forEach((btn) => createBtnDelete(btn));并使用li.forEach((btn) => createBtnDelete(btn)); sending each li item as arg then, when you create a new button you can call the same function sending the li you created as a arg like this然后将每个 li 项目作为 arg 发送,当您创建一个新按钮时,您可以调用相同的 function 将您创建的 li 发送为这样的 arg

function createListElement() {

        let li = document.createElement("li")
        li.appendChild(document.createTextNode(input.value))
        ul.appendChild(li)
        input.value = ""

      
        // Create a delete button and configure it:
        createBtnDelete(li);
       
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM