jQuery动态创建DOM之后,给新创建的DOM绑定事件。
先上两张图,说明一下将要实现的效果
根据下拉列表的选择的不同,展示不同的内容。
刚开始我的做法是,找到dom元素,直接绑定change事件,结果什么效果没有。
上代码。。
$("#select-type").change(function () {
console.log(1);
if($("#select-type option:selected").text()=="选择题"){
$(".filling-up").css("display","none");
}else{
$(".select-item").hide();
$(".filling-up").css("display","table");
}
});
这么写,压根儿不会打出来,因为js代码执行完了,dom还没创建呢。
后来看了陈三的博客 https://blog.zfanw.com/jquery-dynamic-insert-element-bind-event/
修正了一下
$(document).on("change", "#select-type", function () {
if ($("#select-type option:selected").text() == "选择题") {
$(".filling-up").css("display", "none");
$(".select-item").css("display", "table-row");
} else {
$(".select-item").css("display", "none");
$(".filling-up").css("display", "table-row");
}
});
结果就奇迹般的实现了。感谢陈三大哥的博客,牛批!!!
还没有评论,来说两句吧...