2017-01-29 21 views
2

即时通讯新的jquery,并需要一些帮助,使得待办事项列表添加新项目时,输入被按下。它在你点击按钮时工作,但当按下输入时没有任何事情发生。非常感谢任何帮助。如何在jquery中添加新项目,当按下输入时做列表

<!DOCTYPE html> 
<html> 
<head> 


    </head> 
<body> 

<form name="toDoList"> 
    <input type="text" id="listItem" name="ListItem" /> 
</form> 
<ol> 
</ol> 
<button id="btn2">Add something</button> 
<p>something</p> 
<p>ldldl</p> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 

<script> 
$(function() { 
    $("#btn2").click(function() { 
    var toAdd = $("#listItem").val(); 
    $("ol").append("<li>" + toAdd + "</li>"); 
    }); 
    $("#listItem")keydown(function(e) { 

    if (e.which === 13) { 

     var toAdd = $("#listItem").val(); 
     $("ol").append("<li>" + toAdd + "</li>"); 
    } 
    }); 
}); 

$(document).on('dblclick', 'li', function() { 
    $(this).toggleClass('strike').fadeOut('slow'); 
}); 



</script> 


</body> 
</html> 
+0

'$( “#的listItem”)。的keydown()',你有语法错误 – Roljhon

+0

方法(如'.keydown()')应该由一个点之前。 –

回答

0
  • 你缺少点在你的筑巢方法.keydown
  • 你错过了一个event.preventDefault应该防止的形式提交:

$(function() { 
 

 
    $("#btn2").click(function() { 
 
    var toAdd = $("#listItem").val(); 
 
    $("ol").append("<li>" + toAdd + "</li>"); 
 
    }); 
 

 
    $("#listItem").keydown(function(e) { 
 
    if (e.which === 13) { 
 
     e.preventDefault(); // Don't submit the form 
 
     $("ol").append("<li>" + this.value + "</li>"); // append this.value 
 
     this.value = ""; // reset the value field 
 
    } 
 
    }); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form name="toDoList"> 
 
    <input type="text" id="listItem" name="ListItem" /> 
 
</form> 
 
<ol> 
 
</ol> 
 
<button id="btn2">Add something</button>

但是嘿...

$(function() { 
 
    
 
    var $input = $("#listItem"), 
 
     $list = $("ol"); 
 
    
 
    // Don't repeat yourself. Use functions! 
 
    
 
    function addListItem(e) { 
 
    if(e.type==="keydown" && e.which !== 13) return; 
 
    e.preventDefault(); // Don't submit form 
 
    $list.append("<li>" + $input.val() + "</li>"); 
 
    $input.val(""); // Reset input field 
 
    } 
 
    
 
    $("#btn2").click(addListItem); 
 
    $("#listItem").keydown(addListItem); 
 

 
    // See the beauty? now you know they both perform the same 
 
    // addListItem() task and you only have to change the code in one place 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form name="toDoList"> 
 
    <input type="text" id="listItem" name="ListItem" /> 
 
</form> 
 
<ol></ol> 
 
<button id="btn2">Add something</button>

相关问题