我查看了所有其他问题,但没有一个问题解决了我的问题。我想在动态插入的元素上运行.click()函数。我尝试了.on('click', function() { } )
,.live('click', function() { } )
,但无济于事。这是我的代码。我在javascript页面底部遇到问题,您可以在其中看到$('div#second').live('click', function () { this.remove(); });
。非常感谢您的帮助
/*global $ */
/*jslint devel: true */
$(document).ready(function () {
"use strict";
$('#check').click(function () {
if ($('#second').length > 0) {
if ($(".bool").length === 0) {
$('#initial').prepend('<p class="bool" id="t">True</p>');
}
else {
if ($('#f').length > 0) {
$('.bool').remove();
$('#initial').prepend('<p class="bool" id="t">True</p>');
alert('It is now true!');
}
else {
alert('It\'s still true!');
}
}
}
else {
if ($('.bool').length === 0) {
$('#initial').prepend('<p class="bool" id="f">False</p>');
}
else {
if ($('#t').length > 0) {
$('.bool').remove();
$('#initial').prepend('<p class="bool" id="f">False</p>');
alert('It is now false!');
}
else {
alert('It\'s still false!');
}
}
}
});
$('#add').click(function () {
if ($('#second').length === 0) {
$('#initial').append('<div id="second">Hey</div>');
}
else {
alert('You can only add one!');
}
});
$('div#second').live('click', function () {
this.remove();
});
$('#clear').click(function () {
if ($('#second').length > 0) {
$('#second').remove();
}
if ($('.bool').length > 0) {
$('.bool').remove();
}
});
});
&#13;
.button {
width: 50px;
height: 20px;
background-color: blueviolet;
border-radius: 5px;
text-align: center;
color: white;
display: inline;
}
#second {
color: darkslategrey;
font-weight: bolder;
background-color: lightgray;
width: 50px;
height: 20px;
text-align: center;
border-radius: 10px;
}
#t {
color: green;
}
#f {
color: red;
}
.bool {
font-weight: bolder;
}
&#13;
<script src="http://code.jquery.com/jquery-3.2.1.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" src="jquery-3.2.1.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="add" class="button">Add</div>
<div id="check" class="button">Check</div>
<div id="clear" class="button">Clear</div>
<p id="initial">Hello</p>
<style>
</style>
</body>
</html>
&#13;