亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

添加在javascript中添加列表的enterkeypress功能,并在todo中正確組織列表樣式

添加在javascript中添加列表的enterkeypress功能,并在todo中正確組織列表樣式

侃侃爾雅 2023-10-04 17:03:03
我想為我的 TODO 列表項目在 Javascript 中添加Enter 函數,在其中我可以按 Enter 鍵并且應該添加該項目,現在我只能通過添加按鈕添加列表。其次,我想通過提供一些樣式來正確組織 TODO 列表的列表?,F在看起來不太好。現在我的 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 關注
  • 120 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號