<!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.
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();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With