1. jQuery事件(其他事件语法相似)
- 单击事件(click):
//对象自动单击
$("div").click();
- 监听用户单击:
$("div").click(function(){
alert('手动点击');
})
- 改变事件(change)
//监听改变事件
$("select").change(function(){
console.log('select下拉选项改变了')
})
2. this
this 与 $(this)
this
是js的dom对象
表示操作当前对象
$(this)
是jquery的对象
表示操作的当前对象
区别:
js 对象表示操作
js的属性
jquery 对象表示操作jquery的方法
使用:
//监听改变事件
$("select").change(function(){
//获取当前操作对象$("select") - js方式
this;
//获取当前操作对象$("select") - jquery方式
$(this);
})
实战示例:
<div>这是一个div标签</div>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
//JS方式
var obj = document.getElementsByTagName('div')[0];
obj.addEventListener('click', function () {
alert('javascript')
console.log(this);//输出: <div>这是一个div标签</div>
})
var obj = $("div");
obj.click(); //让对象自动单击
//jQuery方式
obj.click(function () { //手动点击
alert('jQuery');
//输出一个jQuery对象,包含原生JS对象和封装的所有jQuery方法
console.log($(this));
});
</script>