我有空div,用jQuery函数追加另一个div:
<div id="files_wrapper"> //comes on start
<div id="delete">delete</div> //will be dynamically created
</div>
我希望点击一下事件:
$(document).ready(function() {
$("#delete").click(function(){
console.log("delete");
});
}
但点击没有任何反应。如何使它工作?
答案 0 :(得分:0)
它是一个ID,所以你用#符号跟着它。
所以这样:
$(document).ready(function(){
$("#delete").click(function(){
alert("Deleted")
$(this).fadeOut(500);
})
})
&#13;
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<div id="files_wrapper">
<button id="delete">Delete</button>
</div>
</html>
&#13;
答案 1 :(得分:0)
我找到了答案:
$(document).on('click', '#delete', function() {
console.log("delete");
});
答案 2 :(得分:0)
HTML:据我所知,你是从这样开始的......
<div id="files_wrapper">Stuff in here</div>
然后,您可以添加一些按钮,在您的应用程序中创建一个新按钮:
<div class="action add" data-type="file-delete">Add Option (Delete)</div>
JavaScript:你需要添加一些脚本来添加一个按钮,它本身就是一个监听器。
// Find your application section
var app = $('#files_wrapper');
// Make an element to clone
var deleteFile = $('<div>').addClass('action delete').html('Delete file');
// Find your trigger that adds the button
$('.action.add[data-type="file-delete"]').on('click.fileaction', function () {
// Clone your template button
var deleteButton = deleteFile.clone();
// Add your listener that reponds to the delete button being pressed
deleteButton.on('click.delete-file', function () {
$(this).toggleClass('clicked')
})
// Add it to the application
app.append(deleteButton)
})
您希望使用jQuery构建DRY应用程序。