首页 > 如何将当前对象作为参数传给onclick的函数

如何将当前对象作为参数传给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;
    }
}



不能這樣使用 thisthis 為關鍵字不能當作參數名

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

<body>
<input name="auto-backup" id="auto-backup" type="checkbox"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$("#auto-backup").click(function(){
    if (this.checked) {
        this.value=1;
    } else {
        this.value=0;
    }
});
</script>
</body>

你用的this是jquery 没库跑不了,你自己看看。


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

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

<input id="in" onclick="change(this)" type="checkbox">sss</input>

<script type="text/javascript">
    function change(that) {
        if (that.checked) {console.log("1");}
        else { console.log("2");}
    }
</script>

function changeValue(el) {
    if (el.checked) {
        el.value=1;
        
    } else {
        el.value=0;
    }
}
【热门文章】
【热门文章】