踩坑之前的代码:
1
2
3
4
5
6
7
8
9
| // HTML
<a href="javascript:;" onclick="follow(123)" class="btn btn-warning btn-sm btn-flat">OK</a>
// JS
<script>
function follow(id){
console.log($(this));
$(this).addClass('success'); // 这个success是添加不上去的
}
</script>
|
填坑:如果onclick
属性没有传入this
对象,则在函数定义中不能使用$(this)
1
2
3
4
5
6
7
8
9
10
11
| // HTML
<a href="javascript:;" onclick="follow(this)" class="btn btn-warning btn-sm btn-flat" data-id="123">OK</a>
// JS
<script>
// 这个地方的which不能写成this,会报错
function follow(which){
console.log($(which));
$(which).addClass('success'); // ok
$(which).data("id"); //123
}
</script>
|
注意的点:js函数的参数名称不能是this。