为了账号安全,请及时绑定邮箱和手机立即绑定

添加在javascript中添加列表的enterkeypress功能,并在todo中正确组织列表样式

添加在javascript中添加列表的enterkeypress功能,并在todo中正确组织列表样式

侃侃尔雅 2023-10-04 17:03:03
我想为我的 TODO 列表项目在 Javascript 中添加Enter 函数,在其中我可以按 Enter 键并且应该添加该项目,现在我只能通过添加按钮添加列表。其次,我想通过提供一些样式来正确组织 TODO 列表的列表。现在看起来不太好。现在我的 TODOLIST 项目看起来像这样https://i.stack.imgur.com/V1j5z.pngvar add = document.getElementById('add');var removeall = document.getElementById('removeall');var list = document.getElementById('list');//remove all buttonremoveall.onclick= function(){    list.innerHTML= '';}//adding a list elementadd.onclick = function(){    addlis(list);    document.getElementById('userinput').value= '';    document.getElementById('userinput').focus();    }function addlis(targetUl){    var inputText = document.getElementById('userinput').value;    var li = document.createElement('li');    var textNode= document.createTextNode(inputText + ' ');    var removeButton= document.createElement('button');            if(inputText !== ''){        removeButton.className= 'btn btn-xs btn-danger';        removeButton.innerHTML= '×';        removeButton.setAttribute('onclick','removeMe(this)');              li.appendChild(textNode); //onebelowanother    li.appendChild(removeButton);     targetUl.appendChild(li);} else{    alert("Please enter a TODO");}}function removeMe(item){    var p = item.parentElement;    p.parentElement.removeChild(p);}body{    font-family: 'EB Garamond', serif;    padding: 0;    margin: 0;    background-color: beige;}h1{    margin: 40px;}#userinput{    width: 350px;    height: 35px;    display: inline-block;}.btn{    margin: 20px 5px;}.form-control{    margin: 0 auto;}ul{    list-style: none;}
查看完整描述

2 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

只需将所有inputs 和buttons包装在form标签内,如下所示:


<form id="...">

<input type="text" id="userinput" class="form-control" placeholder="what you need to do" onkeydown="return searchKeyPress(event);">

<button type="submit" class="btn btn-success" id="add">Add a TODO</button>

</form>

并替换它:


add.onclick = function(){...})


form = document.getElementBy...

form.addEventListener('submit', function() {...})

还要尽量避免书写add.onclick和使用addEventListener。这样您就可以拥有多个侦听器,轻松删除它们,并且总体上拥有更多控制权。


查看完整回答
反对 回复 2023-10-04
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

使用事件监听器来监听输入中的按键(13 是回车键):


var input = document.getElementById("userinput");


input.addEventListener("keyup", function(event) {

  if (event.keyCode === 13) {

    event.preventDefault();

    searchKeyPress(event);

  }

});


查看完整回答
反对 回复 2023-10-04
  • 2 回答
  • 0 关注
  • 57 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信