If you have already injected some Javascript dynamically in a page (possibly because you cannot modify the original scripts directly), you may have realised the order in which Javascript functions are triggered is dependent on the order of declaration. Hence, if you try and bind a new "onclick" handler on a button for which another function has already been bound, the latter will be executed before yours. Here is a simple trick to reorder the order of execution.
Say your original code looks like so:
<script>
function showAlert(message){
alert(message);
}
</script>
[...]
<input type=text id="myButton" onClick="showAlert(this.value);" />
function showAlert(message){
alert(message);
}
</script>
[...]
<input type=text id="myButton" onClick="showAlert(this.value);" />
You can't modify the HTML part and yet you want to execute a new function of your own before the alert message of showAlert is sent, for instance the following one:
The principle, very simple, is simply to unbind everything then reattach functions in the order you want. Below is how it woud look (note that make it even easier, I'm using jQuery):
function changeMessage(newMessage){
document.getElementById("myButton").value=newMessage;
}
document.getElementById("myButton").value=newMessage;
}
The principle, very simple, is simply to unbind everything then reattach functions in the order you want. Below is how it woud look (note that make it even easier, I'm using jQuery):
<script>
function showAlert(message){
alert(message);
}
function changeMessage(newMessage){
document.getElementById("myButton").value=newMessage;
}
$(document).ready(function(){
document.getElementById("myButton").onclick=null;
$("#myButton").click(function(){
changeMessage("test");
showAlert(myButton.value);
});
});
</script>
[...]
<input type=text id="myButton" onClick="showAlert(this.value);" />
function showAlert(message){
alert(message);
}
function changeMessage(newMessage){
document.getElementById("myButton").value=newMessage;
}
$(document).ready(function(){
document.getElementById("myButton").onclick=null;
$("#myButton").click(function(){
changeMessage("test");
showAlert(myButton.value);
});
});
</script>
[...]
<input type=text id="myButton" onClick="showAlert(this.value);" />
Commentaires
Enregistrer un commentaire