Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my jQuery empty doesn't work? [duplicate]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<body>

<button type="button" onclick="submit();">launch</button>
<button type="button" onclick="clear();">clear</button>


<div>
    Result:<br>
    <div id="result">
    </div>
</div>
<script>
    function clear() {
        $('#result').empty()
    }

    function submit() {
        $('#result').append('<div>xxxxx</div>')
    }
</script>
</body>
</html>

Launch button works well but clear doesn't. I run $('#result').empty() in console, it clear the div as expected.

You may debug my code in jsfiddle.

like image 649
Sayakiss Avatar asked Apr 12 '16 13:04

Sayakiss


1 Answers

Calling clear() in an inline handler is actually calling something else called document.clear(), and so your function is never called.

This is because in an inline handler, document is in scope before window and your clear function is in the global scope, which is window for browsers.

You can change the function name to something else

<button type="button" onclick="myClear();">clear</button>

function myClear() {
    $('#result').empty()
}

Alternatively I would prefer to avoid inline handlers and also avoid polluting the global scope.

$(function(){
    function clear() {
        $('#result').empty();
    }

    $('.clear').click(function(){
        clear();
    });
});
like image 88
MrCode Avatar answered Nov 09 '22 10:11

MrCode