我有以下 HTML 代码:
<div id="image-preview1" class="col-xs-2 ">
<div id="buttonPlace1"></div>
<div>
<label for="image-upload1" id="image-label1">Upload photo</label>
<input type="file" name="image" id="image-upload1">
</div>
</div>
和
$('#image-upload1').change(function() {
$('#buttonPlace1').append("<button id='closeBtn1' onclick='btnRemove1()' class='btn deleteButton'>X</button>");
})
function btnRemove1(){
$('#buttonPlace1').empty();
}
这很好用。单击时添加和删除按钮。
但是当我从 <button>
中删除 onclick 事件时并更改btnRemove()
至:
$('#closeBtn1').click(function() {
$('#buttonPlace1').empty();
})
点击删除按钮停止工作。 我刚开始接触 JS 和 jQuery,但我不明白。 请帮忙>:|
最佳答案
1.由于按钮是动态添加的所以需要使用event-delegation
2.我的假设:-您需要删除上传的文件以及单击删除按钮时的按钮。(我希望您希望这样)
如下所示:-
$(document).on('click','#closeBtn1',function() {
$('#image-upload1').val('');
$(this).remove();
});
工作片段:-
$('#image-upload1').change(function() {
$('#buttonPlace1').append("<button id='closeBtn1' class='btn deleteButton'>X</button>");
});
$(document).on('click','#closeBtn1',function() {
$('#image-upload1').val('');
$(this).remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image-preview1" class="col-xs-2 ">
<div id="buttonPlace1"></div>
<div>
<label for="image-upload1" id="image-label1">Upload photo</label>
<input type="file" name="image" id="image-upload1">
</div>
</div>
关于javascript - .empty() 不在 $ ('#xxxx' ).click(xxx 但从直接 js 函数调用时工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50058882/