jq append()新增的dom如何控制
新增的dom无法使用jquery如何解决
javascript
$("#addVolumePrice").click(function(){ $("#thisVolumePrice").append( '<br/> <a class="redVolumePrice" href="javascript:void(0)" >[-]</a>' + '优惠数量 <input type="text" class="input-mini"/>' + '优惠价格 <input type="text" class="input-small"/>' ); }); $(".redVolumePrice").live("click",function(){ alert('111'); }); $(".redVolumePrice").on("click",function(){ alert('111'); });
hi上面的写法在事件绑定的时候,dom还不存在,所以事件帮不上,要解决这个问题,可以利用冒泡原理,把事件绑定在父元素上,然后判断target就好了,这是原理在jq中可以用live实现,但是在 1.7后live就废弃了,你上面不起作用可能是版本的问题,可以使用delegate(委托、代理)
$('#thisVolumePrice').delegate('click', '.redVolumePrice', function(evt) {
console.log(evt); // 去看看 console 里打印的 evt 对象,里面有一些东西很有用。
});
其实现在推崇用on,on也提供类似的接口
$('#thisVolumePrice').on('click', '.redVolumePrice', function(evt) {
console.log(evt); // 去看看 console 里打印的 evt 对象,里面有一些东西很有用。
});
这么写试试吧:
javascript
$('#thisVolumePrice').on('click', '.redVolumePrice', function(evt) { console.log(evt); // 去看看 console 里打印的 evt 对象,里面有一些东西很有用。 });
$(".redVolumePrice").live("click",function(){
alert('111');
});
$(".redVolumePrice").on("click",function(){
alert('111');
});
这样当然不行的,$("outerSelector").on('eventType','selector',function(){});
outerSelector 是一个一直存在的DOM, selector是你要监听点击的节点;
所以正确的写法是
$("#thisVolumePrice").on("click",'.redVolumePrice',function(){
alert('111');
});
具体原理 可以搜索 javascript 事件代理
//多谢@nightire的提醒