最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom events - How to pass parameter to the attachEvent Javascript function - Stack Overflow

programmeradmin3浏览0评论

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 the event object? – SLaks Commented Apr 18, 2010 at 19:40
Add a ment  | 

3 Answers 3

Reset to default 5

You 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

发布评论

评论列表(0)

  1. 暂无评论