使用以下代码行不会在我的列表项上触发简单的点击事件:
$("ol > li").on("click", listItemClickEventHandler);
要解决此问题,我先将对查询选择器的引用进行缓存,然后在其上调用on
函数。
查询选择器确实返回了一个对象,但我不能确定这是否是设置处理程序的正确对象,除了我过去做过一百万遍并且已经起作用的事实。
function showAllCookies() {
$("ol").empty();
let all = []; //getAllCookies();
if (all) {
for(let cookie of all) {
$("ol").append(`<li>${cookie}</li>`);
}
} else {
$("ol").append(`There are no cookies to display.`);
}
}
$(btnSave).on("click", function(event) {
// create cookie
});
$("input[type='text']").on("keyup", function(event) {
// trigger save
});
$("ol > li").on("click", listItemClickEventHandler);
function listItemClickEventHandler(event) {
let key = event.target.id;
$("#txtCookieName").val(key);
// to do
$("#txtCookieValue").val("");
}
showAllCookies();
.header {
font-size: 1.4rem;
font-weight: bold;
}
input[type="text"] {
width: 200px;
margin: 10px;
}
#errorMessage {
color: red;
}
li:hover {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.js"></script>
<div>
<div class = "header">All Cookies</div>
<ol>
</ol>
</div>
<div>
<div class = "header">Enter a key and value to create a new cookie or to update an existing one</div>
<div id = "errorMessage"></div>
<input type = "text" id = "txtCookieName" value = "" placeholder="cookie name"/><br />
<input type = "text" id = "txtCookieValue" value = "" placeholder="cookie value"/>
<button id = "btnSave">Save</button>
</div>
答案 0 :(得分:1)