解決方案:將普通事件改為.on()委托事件
示例:
$('.btn1').click(function(){ //code }) //普通綁定事件
$(document).on('click','.btn1',function(){//code }) //on綁定事件
原因:動態添加的HTML元素是在CSS,JS代碼加載完成后再添加的HTML頁面。在瀏覽器解析這些通過ajax請求到后台
返回的數據,再根據返回的結果動態生成HTML頁面時,這些綁定事件的標簽元素還沒有生成。而普通.click事件只能綁定
靜態元素。用on方法支持動態綁定元素。
CSS無效解決辦法:
<div class="box"> <input type="text" name="" value="已經存在的input"> </div> <button>添加input</button>
.box{ width: 500px; height: 300px; border-radius:8px; border:1px solid #f0f; margin-bottom: 20px; padding: 5%; } .box input{ border:0px; background: skyblue; color: #fff; height: 35px; border-radius: 8px; }
var box = $('.box'); var appendHtml = '<input type="text" name="" value="追加的input">'; box.append(appendHtml); // 解決樣式不生效 $(".box").trigger("create");
