真真實痛苦了,之前測試的時候明明也是這樣寫的是可以的,后來就莫名其妙的不可以了,不可以了怎么辦,盤他,至於原因就隨風吧,找不到之前為什么可以。
解決:on方法中要找到原選擇器(如例.info),再找到動態添加的選擇器(如列.delete)。
<!DOCTYPE html PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"
>
<html>
<head>
<meta http-equiv=
"Content-Type"
content=
"text/html; charset=UTF-8"
>
<title>測試</title>
<script type=
"text/javascript"
src=
"../resources/js/jquery-1.11.1.min.js"
></script>
<script type=
"text/javascript"
>
$(
function
(){
//動態添加
$(
".add"
).on(
"click"
,
function
(){
console.log(
"進來了"
);
$(
".info"
).append(
'<div class="delete"><h3>單擊我來刪除我</h3></div>'
);
});
//對動態添加的元素添加事件-刪除
$(
".info"
).on(
"click"
,
".delete"
,
function
(){
console.log(
"進來了Delete!"
);
$(
this
).remove();
});
});
</script>
</head>
<body>
<h2 class=
'add'
>單擊我添加動態元素</h2>
<div class=
"info"
></div>
</body>
</html>