I have to pass a parameter the validateNum
Javascript function (e.g. num1, num2)
if (num1.attachEvent) {
num1.attachEvent("onkeypress", validateNum);
}
How to pass? Can I get a code sample?
I have to pass a parameter the validateNum
Javascript function (e.g. num1, num2)
if (num1.attachEvent) {
num1.attachEvent("onkeypress", validateNum);
}
How to pass? Can I get a code sample?
Share Improve this question edited Oct 4, 2021 at 21:22 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Apr 18, 2010 at 19:33 minilminil 7,14516 gold badges51 silver badges57 bronze badges 1-
Does
validateNum
use theevent
object? – SLaks Commented Apr 18, 2010 at 19:40
3 Answers
Reset to default 5You need to make an anonymous currier:
num1.attachEvent("onkeypress", function() { return validateNum(num1, num2); });
Aside from SLaks' answer, in ECMAScript 5th Edition implementations you can use the bind
method:
num1.attachEvent("onkeypress", validateNum.bind(null, num1, num2));
In implementations that don't support the method you can either use the Prototype JS framework or just add the method to the Function prototype with this snippet:
if (!('bind' in Function.prototype)) {
Function.prototype.bind= function(owner) {
var that= this;
var args= Array.prototype.slice.call(arguments, 1);
return function() {
return that.apply(owner,
args.length===0? arguments : arguments.length===0? args :
args.concat(Array.prototype.slice.call(arguments, 0))
);
};
};
}
Finnaly i get solution to pass 'this' as a parameter. if anyone get here search for this(kkkk)....
<input type="checkbox" name="ch_aceito" id="ch-aceito" value="1" />
<script type="text/javascript">
"use strict";
var el = document.getElementById("ch-aceito");
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
//alert(isIE());
if (document.addEventListener) {
//console.log('here');
el.addEventListener("click", getPost, false);
} else {
el.attachEvent("onclick", function() {
getPost(el);
});
}
function getPost(el){
if(isIE() && isIE() <= 8){
alert(el.value);
} else {
alert(this.value);
}
}
</script>
I get isIE from here:
Detect IE version (prior to v9) in JavaScript