Jquery/js引入的button的onclik事件只触发一次

382 阅读1分钟

目标描述:
通过监听button的click事件,新增内容

问题描述:
第一点击的时候,成功新增成功,但第二次就无法触发

$('.addDetail').on('click', function () {
	let addStr = `<view class="item"><input type="text" placeholder="详情名"> : <input type="text" placeholder="详情值"></view>`;
	console.log($(babel).html())
	addTotal = $(babel).html() + addStr
	$(babel).html(addTotal)
})

问题原因:
原因是通过on来绑定click事件如上述代码,只会监听一次,之后就会丢失

解决方法:

$(document).off("click",".addDetail").on("click",".addDetail", function() {
	let addStr = `<view class="item"><input type="text" placeholder="详情名"> : <input type="text" placeholder="详情值"></view>`;
	console.log($(babel).html())
	addTotal = $(babel).html() + addStr
	$(babel).html(addTotal)
})