目录
使用jquery的on函数
父选择器.on('事件类型名称','添加事件元素名的判定依据',function()){ //js语句 };(不但能给固有元素添加事件,也能给动态生成的元素添加事件)
(父元素:必须时固有元素,可以是直接父元素,也可以是间接父元素)
(事件类型:跟事件数据属性和事件函数意义对应)
(子元素:目标元素,跟父选择器构成一个父子选择器)
注意:使用使用jquery对象判定事件时,对于用在动态元素上,事件可能会失效,而固有元素则没问题
使用例子:
添加事件的标签:
添加事件标签的父标签:
添加事件:
//鼠标悬停事件--------图标显示(只能固有标签加)----------传统方法
// $(".remarkDiv").mouseover(function(){
// //子子标签
// $(this).children("div").children("div").show();
// });
//动态添加的页面元素也能触发事件--------------------------on方式
$("#remarkDivList").on('mouseover','.remarkDiv',function () {
$(this).children("div").children("div").show();
})
//鼠标移除事件--------图标隐藏
// $(".remarkDiv").mouseout(function(){
// $(this).children("div").children("div").hide();
// });
$("#remarkDivList").on('mouseout','.remarkDiv',function () {
$(this).children("div").children("div").hide();
})
//鼠标悬停事件-----颜色变红
// $(".myHref").mouseover(function(){
// $(this).children("span").css("color","red");
// });
$("#remarkDivList").on('mouseover','.myHref',function () {
$(this).children("span").css("color","red");
})
//鼠标移除事件--------颜色恢复
// $(".myHref").mouseout(function(){
// $(this).children("span").css("color","#cbc6c6");
// });
$("#remarkDivList").on('mouseout','.myHref',function () {
$(this).children("span").css("color","#cbc6c6");
})