今天要讲的是jquery 为未来元素绑定事件,做了一个页面,因为元素都是通过ajax请求得来渲染的,故称未来元素。之前没有进行特殊操作,就当一般元素来写事件,但却没有效果。代码如下:
html 主要部分:
<div class="box"></div>
<script id="t1" type="text/html">
{{each xiaolei as index}}
<dd>
<div class="picture">
<img src="{{index.picture}}" />
</div>
<div class="dishes">
<p class="dish_title">{{index.name}}</p>
<div class="under_dishes">
<div class="under_content">
<p class="sales">月售{{index.monthSale}}</p>
<p class="price">¥<span>{{index.price}}</span></p>
</div>
<p class="add"> <i class="icon iconfont icon2"></i> <span class="nums"> 1 </span> <i class="icon iconfont icon1"></i> </p>
</div>
</div>
</dd>
{{/each}}
</script>
这是一段arttemplate 模板渲染,本来小编之前是用的 javascript字符串拼接,但是之后渲染的元素绑定事件无效,还以为是字符拼接的问题所以就用了arttemplate 模板渲染,虽然两者效果相差无几,但是小编还是推荐使用模板渲染哈。或者使用js框架,总之尽量不要使用字符串拼接~
下面是javscript代码:
function rightDataRender(smallClassfy){
var html="";
var xiaolei;
//var classfyArray;
$.ajax({
url:"js/orderMeal.json",
type:"get",
dataType:"json",
async:true,
data:{},
error:function(){
console.log("对不起,请求出错!");
},
success:function(data){
switch(smallClassfy){
case 0:xiaolei=data.recommend;
break;
case 1:xiaolei=data.specialtyCoffee;
break;
case 2:xiaolei=data.tea;
break;
}
console.log(xiaolei);
var xiaoleit1 =template("t1",{xiaolei:xiaolei});
$(".box").html(xiaoleit1);
}
})
}
在这里我使用的是一个ajax本地请求,请求出json数据。然后再做判断,分出循环体:xiaolei ,然后再回到模板渲染
var xiaoleit1 =template("t1",{xiaolei:xiaolei});
$(".box").html(xiaoleit1);
然后现在要为元素".add .icon1"绑定点击事件。
开始写的是:
$(".add .icon1").click(function(){
//do sth
});
这样不行,对于未来元素没有效果。
后来写成:
$(".add .icon1").on("click",function(){
//do sth
})
这样也不行,还是未绑定成功。
最后查阅资料,经过别人的指点,才想起来应该要这样绑定:
$("body").on("click",".add .icon1",function(){
//do sth
})
这样才绑定成功,之前学过,后来忘记了,印象中老以为是第二种。忽略忽略,看来知识还是要不断温习!