对此我是陌生的,尝试学习任何建议将不胜感激。
在下面粘贴的HTML文档中,我试图使用父元素来捕获keydown事件。该代码适用于以下代码
document.addEventListener('keydown',checkKeyPressed, false);
但不适用于
document.getElementById('menuItemsParent').addEventListener('keydown',checkKeyPressed, false);
这是整个页面
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/stylesheets/style.css">
</head>
<body>
<div id="menuItemsParent" ></div>
<input name="firstname" type="text">
<p id = "dateOfMenu">Click button to add menu Item for Friday         <button id="MondayButton" onclick="myFunction('end_dateOfMenu')">Add Item</button></p>
<p id = "end_dateOfMenu"> </p>
<p id = "Saturday">Click button to add menu Item for Saturday      <button id="SaturdayButton" onclick="myFunction('end_saturday')">Add Item</button></p>
<p id = "end_saturday"> </p>
<p id = "Sunday">Click button to add menu Item for Sunday        <button id="SundayButton" onclick="myFunction('end_sunday')">Add Item</button></p>
<p id = "end_sunday"> </p>
<p id = "Monday">Click button to add menu Item for Monday       <button id="MondayButton" onclick="myFunction('end_monday')">Add Item</button></p>
<p id = "end_monday"> </p>
<p id = "Tuesday">Click button to add menu Item for Tuesday       <button id="TuesdayButton" onclick="myFunction('end_tuesday')">Add Item</button></p>
<p id = "end_tuesday"> </p>
</form>
<p id = "Wednesday">Click button to add menu Item for Wednesday  <button id="WednesdayButton" onclick="myFunction('end_wednesday')">Add Item</button></p>
<p id = "end_wednesday"> </p>
<p id = "Thursday">Click button to add menu Item for Thursday     <button id="ThursdayButton" onclick="myFunction('end_thursday')">Add Item</button></p>
<p id = "end_thursday"> </p>
</div>
<h2>Not in div element</h2>
<form id="menuform" >
<input type = "button" value="Create Menu">
</form>
</body>
<script>
var idIncrement = 1;
document.addEventListener('keydown',checkKeyPressed, false);
//document.getElementById('menuItemsParent').addEventListener('keydown',checkKeyPressed, false);
/* Function to create input areas on the form when button clicked */
function myFunction(elemnt_id) {
var i;
var dateOfMenu = document.getElementById(elemnt_id);
var paragraph = document.createElement("P");
document.body.insertBefore(paragraph, dateOfMenu);
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", "");
x.setAttribute("id", elemnt_id + "_" + idIncrement);
idIncrement+=1;
document.body.insertBefore(x, dateOfMenu);
}
function checkKeyPressed(e) {
if (e.keyCode == "65") {
alert("The 'a' key is pressed.");
}
}
</script>
</html>