无法从onclick属性正确调用JavaScript函数 [英] JavaScript function not called from onclick attribute correctly

查看:287
本文介绍了无法从onclick属性正确调用JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重要提示!:我必须使用onclick属性.在我的情况下,在事件侦听器/处理程序上使用Jquery不是一个选择.为什么?我的代码中还有很多其他事情,它们取决于属性及其在代码中的体现.

将警报置于onclick属性中时,警报将按预期方式工作,并且警报将显示在弹出窗口中,并且返回false可以防止通过按按钮提交表单:

When putting alert in onclick attribute it's working as expected and the alert is shown in a popup window and return false prevents the form from being submitted by pressing the button:

<script>
    $().ready(function() {
        $('.pretty .prettycheckbox').click(function () {

            var myType = $('.pretty .prettycheckbox').find("input[class^=car-type]:checked").val();

            if (myType == 1) {
                $('#sendButton').attr("onclick", "alert('Direct!'); return false;");
            } 

            if (myType == 2) {
                $('#sendButton').removeAttr("onclick");
            }

        });
    });
</script>

但是当从onclick属性调用一个函数时,它不起作用:

But it's not working when calling a function from onclick atttribute like:

<script>
    $().ready(function() {
        $('.pretty .prettycheckbox').click(function () {

            var myType = $('.pretty .prettycheckbox').find("input[class^=car-type]:checked").val();

            if (myType == 1) {
                $('#sendButton').attr("onclick", "submitDB(); return false;");
            } 

            if (myType == 2) {
                $('#sendButton').removeAttr("onclick");
            }

        });
    });
</script>

<script>
    $().ready(function(){
        function submitDB() {
            alert('From function!');
        }
    });
</script>

知道为什么吗?

为什么忽略该功能?

推荐答案

您的代码不起作用,因为您遇到了很大的范围问题. onclick属性只能定位全局范围内的函数.就您而言,您的功能不在全局范围内.

Your code doesn't work because you have a big scope problem. onclick attributes can only target functions that are in the global scope. In your case, your function is not in the global scope.

<script>
    $().ready(function(){
        function submitDB() {
            alert('From function!');
        }
    });
</script>

应该是

<script>
        function submitDB() {
            alert('From function!');
        }
</script>

演示: http://jsfiddle.net/ZeLXY/

我仍然不明白为什么学校"会尝试教如何使用jquery添加onclick属性.您完全没有理由希望使用javascript(而不是jQuery)向元素添加onclick属性.

I still don't understand why "school" would try to teach how to add onclick attributes using jquery. There's no reason you would EVER want to add onclick attributes to an element with javascript, much less jQuery.

这篇关于无法从onclick属性正确调用JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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