var html = "<div class=\"radio-box\" style=\"padding-top: 0px;width: 100%\">" + " <input type=\"checkbox\" th:id=\""+uuid+"\" name=\"content\" >" + " <label th:for=\""+uuid+"\" style=\"width: 94%\">\n" + " <input type=\"text\" class=\"form-control\" name=\"content\"/>\n" + " </label>\n" + " <i class=\"fa fa-remove\" style=\"float: right;margin-top: 10px\"></i>\n" + " <br></div>"; $(this).before(html);
例1 樣式
bootstrap checkbox和radio
頁面上bootstrap 的樣式沒有生效
解決辦法:
// 渲染js拼接的radio,checkbox按鈕 $('input[type=checkbox]').iCheck({ labelHover : false, cursor : true, checkboxClass : 'icheckbox-blue', increaseArea : '20%' });
// 渲染js拼接的radio,checkbox按鈕 $('input[type=radio]').iCheck({ labelHover : false, cursor : true, radioClass : 'iradio-blue', increaseArea : '20%' });
例2
點擊事件
此點擊事件無效
$(function () { $(".fa-remove").click(function () { var tr = $(this).parent(); tr.remove(); }) })
原因:
因為append中的節點是在整個文檔加載后才添加的,頁面並不會為未來的元素初始化添加點擊事件,所以使用這種方式動態添加的節點中的點擊事件沒有生效。
解決方案:
事件委托。給所有的類名為.div的元素添加點擊事件,將指定事件綁定在document上,只要而新產生的元素符合指定的元素,就會綁定此事件 ,而且這種方法當頁面需要為多個節點初始化事件的時候,就不需要一個個加onclick事件。
$(document).on("click", ".fa-remove", function () { var tr = $(this).parent(); tr.remove(); })