列表应用回车添加功能引发的作用域与功能失效问题求助
待办列表回车提交功能异常问题
我的待办列表原本运行正常,添加回车按键触发添加列表项的功能后出现异常:
- 将keydown事件监听函数放在
newItem()函数外部时,crossOutButton()、strike CSS样式及sortable()功能因作用域问题无法正常工作; - 将该keydown函数放入
newItem()函数内部时,输入框仅会清空,但没有任何提交动作,且控制台无报错信息。
我推测存在可将所有功能整合到newItem()函数内的解决方案,但目前陷入困境,相关代码如下:
JavaScript代码
function newItem() { //Adds new item to the list let li = $('<li></li>'); let inputValue = $('#input').val(); li.append(inputValue); if (inputValue === '') { alert('You must write something'); } else { $('#list').append(li); //clears input field after selecting 'Add' button $('#input').val(''); } //Crossing out an item from the list of items function crossOut() { li.toggleClass('strike'); } li.on('dblclick', function crossOut() { li.toggleClass('strike'); }); //Adding the delete button 'X' let crossOutButton = $('<crossOutButton></crossOutButton>'); crossOutButton.append(document.createTextNode('X')); li.append(crossOutButton); crossOutButton.on('click', deleteListItem); //Adding class delete (display: none) from css function deleteListItem() { li.addClass('delete'); } //reordering the items $('#list').sortable(); } //keydown function to listen for enter key $(document).ready(function() { $('#input').keydown(function(e) { //initialized variable and set as undefined let inputValue; if (inputValue === '') { alert("You must enter something"); } else { //Enter key holds the value of 13 if (e.keyCode === 13) { let li = `<li>${$(this).val()}</li>`; $('#list').append(li); console.log('Form submitted'); e.preventDefault(); //clears input field after hitting enter $('#input').val(''); } } }) });
HTML代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <form name="toDoList"> <input type="text" name="listItem" id="input"> </form> <div onclick="newItem()" id="button">Add</div> <br/> <ol id="list"></ol>
内容的提问来源于stack exchange,提问作者Bryan
相关产品推荐
相关产品推荐

