javascript - 如何将当前对象作为参数传给onclick的函数

查看:68
本文介绍了javascript - 如何将当前对象作为参数传给onclick的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<input name="auto-backup" id="auto-backup" type="checkbox" onclick="changeValue(this)" />

function changeValue(this) {
    if (this.checked) {
        $(this).value=1;
        
    } else {
        $(this).value=0;
    }
}

上面的代码没有反应

  <input name="auto-backup" id="auto-backup" type="checkbox" onclick="changeValue()" /> 
function changeValue() {
    if (document.getElementById('auto-backup').checked) {
        document.getElementById('auto-backup').value=1;

    } else {
        document.getElementById('auto-backup').value=0;
    }
}

这段代码得到想要的效果了

我的问题是如何把第一段代码实现,用this实现

我直接绑定click函数,下面这段代码搞对了

$("#auto-backup").click(function(){
    if (this.checked) {
        this.value=1;
    } else {
        this.value=0;
    }
});

下面这段代码搞对了
<input name="auto-backup" id="auto-backup" type="checkbox" onclick="changeValue(this)" />
function changeValue(that) {
    if (that.checked) {
        that.value=1;
    } else {
        that.value=0;
    }
}


解决方案

this 是关键字,不能作为函数的参数。改成下面这样就好了。

function changeValue(that) {
    if (that.checked) {
        that.value=1;
    } else {
        that.value=0;
    }
}

这篇关于javascript - 如何将当前对象作为参数传给onclick的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆