1.给input框加一个失去焦点事件:当失去焦点时获取当前对象的属性值.
在YII中贴代码如下:
电话: <?=Html::input('text','tel',$row['mobile'],['id'=>$row['uid'],'onBlur'=>"commit(this)"])?>
js代码如下:
错误代码一:
<script> function commit(obj){ //错误写法一 报错:TypeError: obj.attr is not a function var id = obj.attr('id'); var name = obj.attr('name'); var tel = obj.attr('tel'); alert(id); alert(name); alert(tel); } </script>错误代码二:
<script> function commit(obj){ //错误写法二 报错 无数据 alert显示 undefined var id = $(this).attr('id'); var name = $(this).attr('name'); var tel = $(this).attr('tel'); alert(id); alert(name); alert(tel); } </script>正确写法:
<script> function commit(obj){ //正确写法 var id = obj.id; var name = obj.name; var tel = obj.value; alert(id); alert(name); alert(tel); } </script>原因:this 就是当前对象,谁触发的事件就是谁 获取对象属性的写法: 对象.属性名
扩展:
input标签中 οnclick="test(this)" 在浏览器解析后,会自动转换成 javascript的事件函数
input对象.onclick = function (event) {
test(this)
}
当以对象里的方法的方式调用函数时,函数内的 this 是调用该函数的对象
当函数被用作事件处理函数时,它的this指向触发事件的元素
2.给input框添加两个事件,获取焦点事件时显示边框,失去焦点时隐藏边框
HTML:代码 电话: <?=Html::input('text','mobile',$row['mobile'],['style'=>"border:none",'onBlur'=>"commit(this)",'onClick'=>"show(this)"])?>
js代码:
<script> //显示边框 function show(obj){ obj.style.border = "1px solid black"; } //隐藏边框 function commit(obj){ obj.style.border = "none"; } </script>