简体   繁体   English

JavaScript事件处理程序范围和此

[英]JavaScript event handler scope and this

If I want to dynamically add an event handler to an HTML element, and not discard or break any existing event handler. 如果我想动态地向HTML元素添加事件处理程序,而不是丢弃或破坏任何现有的事件处理程序。

The code below will not do that because if the existing handler registered for an event on the element referred to 'this', my chaining of handlers would break that. 下面的代码不会这样做,因为如果现有的处理程序在指向'this'的元素上注册了一个事件,那么我的处理程序链会中断该操作。 I'd actually like to be able to use 'this' in the new handler too if possible, but I could always get around that I guess. 实际上,如果可能的话,我实际上也希望能够在新处理程序中使用“ this”,但是我想我总是可以解决这个问题。

<script type="text/javascript">

    function oldHandler()
    {
         alert("old handler; this.value=" +this.value);
    }

</script>

<form name="test1" id="test1">

    <fieldset>
        <legend>My Test</legend>
        <ol>
            <p>
            <li>
                <label for="tf1">Test Field 1</label>
                <input id="tf1" onchange="existingHandler();" name="tf1"/>
            </li>
        </ol>
    </fieldset>

</form>

<script type="text/javascript">

    function myAddHandler(element, event, newHandler)
    {
        var existingHandler = element[event];
        element[event] = function() {
                            newHandler();
                            existingHandler();
                         }
    }

    function myOnChangeHandler()
    {
        alert("new handler; this.value=" +this.value);
    }

    myAddHandler(document.getElementById('tf1'), "onchange", myOnChangeHandler);

</script>

Thanks. 谢谢。

What you want to do is either inject the value of this 你想要做什么或者是注入的价值this

element[event] = function () {
  old.apply(this, arguments);
  new.apply(this, arguments);
};

Or use real event listeners that don't overwrite each other 或使用不会互相覆盖的真实事件监听器

element.addEventListener(event, new);

To point 'this' back to the right object I do this at the top of my eventhandlers: 为了将“ this”指向正确的对象,我在事件处理程序的顶部执行以下操作:

var that = e.target || e.srcElement; 

'that' is now pointing to the object that triggered the event “ that”现在指向触发事件的对象

Make your life easier. 让您的生活更轻松。 Attach and detach events by using a JavaScript framework. 通过使用JavaScript框架附加和分离事件。 eg in jQuery $("#someID").bind("click", clickHandler); 例如在jQuery $("#someID").bind("click", clickHandler); . Or if you don't want to use jQuery there are plenty of other JavaScript frameworks out there: MooTools, Dojo etc. 或者,如果您不想使用jQuery,则还有很多其他JavaScript框架:MooTools,Dojo等。

Check out http://api.jquery.com/category/events . 查看http://api.jquery.com/category/events Of course you can do this with old school JavaScript but then you need to manage all the cross-browserness of attaching/detaching events. 当然,您可以使用旧式JavaScript执行此操作,但是您需要管理附加/分离事件的所有跨浏览器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM