1
Test scenario
index
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<title></title>
<script type="text/javascript">
function carregar() {
$.ajax({
url: 'inc.php',
success:function(response){
$('#ret').html(response).show();
},
error:function(xhr, ajaxOptions, thrownError){
console.log(thrownError);
}
});
}
</script>
</head>
<body>
<div>
<button onclick="carregar()">Carregar</button>
</div>
<hr>
<div id="ret"></div>
</body>
</html>
inc.php
<script type="text/javascript">
$(document).keydown(function (e) {
if (e.altKey && e.keyCode == 67) {
clone();
}
});
function clone() {
const template = $('#elementos > #el').last();
const novo = template.clone();
$('#elementos').append(novo);
}
</script>
<div>
<button onclick="clone()">Clonar</button>
<div id="elementos">
<p id="el">Elemento</p>
</div>
</div>
Simulation
The index
, has a button that calls Ajax the content of inc.php
, where it has a function that clones the element with id="el"
the "clone" button or the "Alt+C" key shortcut".
What happens is that each time you "reload" the content of inc.php
by the "press" button of index
, it adds +1 clone only by shortcut, but not by button, as below:
Doubt
- Why this happens only with the "shortcut" set?
1. Whenever the event
keydown
is used in jQuery, it is added (and not replaced). That is, every time the pageinc.php
is loaded, a new action will be added in the above mentioned event. 2. This does not occur with the "clone" button, because the functiononclick
will always have only one command and the function will be replaced. I do not know if I understand (anything mount a gif).– Valdeir Psr
I believe you reversed the text (the title is ok): who duplicates the shortcut and not the :D button
– Sam
@Sam true! Thanks!! Kkk
– rbz