Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

jquery - JavaScript function not called from onclick attribute correctly

IMPORTANT!: I have to use onclick attribute. Using Jquery on event listener/handler is not an option in my case. Why? I have a lot of other things in my code that are dependent on the attribute and its manifestation in the code.

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>

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>

Any idea why?

Why is the function ignored?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

should be

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

Demo: http://jsfiddle.net/ZeLXY/

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...