javascript - 删除以避免递归

标签 javascript recursion

我一直在阅读“Javascript:Definitive Guid”,其中一个例子让我困惑。为什么处理 IE 的代码需要“this.onpropertychange = null”以避免递归。递归将如何发生?为什么我们不需要以同样的方式处理处理其他浏览器的“upcase”函数?谢谢。

//Example 17-7. Using the propertychange event to detect text input
function forceToUpperCase(element) {
    if (typeof element === "string") element = document.getElementById(element);
    element.oninput = upcase;
    element.onpropertychange = upcaseOnPropertyChange;
    // Easy case: the handler for the input event
    function upcase(event) {
        this.value = this.value.toUpperCase();
    }
    // Hard case: the handler for the propertychange event
    function upcaseOnPropertyChange(event) {
        var e = event || window.event;
        // If the value property changed
        if (e.propertyName === "value") {
            // Remove onpropertychange handler to avoid recursion
            this.onpropertychange = null;
            // Change the value to all uppercase
            this.value = this.value.toUpperCase();
            // And restore the original propertychange handler
            this.onpropertychange = upcaseOnPropertyChange;
        }
    }
}

最佳答案

因为当事件处理程序更改“value”属性时,它将触发另一个“propertychange”事件。因此,一旦第一个事件处理程序完成,浏览器就会立即再次调用它。

(在这种情况下,这并不是真正的“递归”,它只是一个无限循环。)

第一个“简单”处理程序正在响应“输入”事件,更新“值”属性不会触发其中一个事件。但是,它会触发“propertychange”事件,因此在该处理程序中也执行相同的操作不会有什么坏处。

关于javascript - 删除以避免递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20304061/

相关文章:

javascript - jQuery 背景幻灯片

algorithm - 如果您每天最多可以观看 3.00 时长的电影,则完成观看给定时长数组的所有电影所需的最少天数

java - 合并排序函数混淆中的两次递归调用

javascript - 删除 React 中内联 block 元素之间的空格

javascript - JavaScript 函数中的 ajax() 调用

python - Django:将表单放入表单(递归...)

java - 递归开关返回字符串

Java 递归归并排序

javascript - 如何隐藏类名动态变化的div元素?

javascript - 如何用分类帐签署比特币 psbt?