简体   繁体   English

Javascript 单元测试中的 setSelectionRange 未按预期运行

[英]Javascript setSelectionRange in unit tests not behaving as expected

I'm using the qunit framework for unit testing interactions with an HTML that I have created programmatically using jquery (ie, var $textarea = $('')) in Chrome.我正在使用 qunit 框架与我在 Chrome 中使用 jquery(即 var $textarea = $(''))以编程方式创建的 HTML 进行单元测试交互。 Here is the code I am using to update the selection in the textarea.这是我用来更新文本区域中的选择的代码。

    TextAreaView.prototype.setSelectionOffsets = function(cursor) {
    var input = this.$textarea.get(0);
    if (!input.setSelectionRange) {
        return;
    }
    if (cursor.start <= input.value.length && cursor.end <= input.value.length) {
        input.focus();
        input.setSelectionRange(cursor.start, cursor.end, "forward");
    }
}

I have verified that I am calling this method with 0 < cursor.start == cursor.end < input.value.length.我已经验证我正在使用 0 < cursor.start == cursor.end < input.value.length 调用此方法。

When I step through with the debugger, everything appears ok - but after it hits the "input.setSelectionRange" line, inspection of the input element shows that the selectionEnd and selectionStart properties=0, the selectionDirection="none"当我使用调试器单步执行时,一切似乎都正常 - 但在它到达“input.setSelectionRange”行后,检查输入元素显示 selectionEnd 和 selectionStart 属性 = 0,selectionDirection =“none”

I'm very confused as to what is happening here.我对这里发生的事情感到很困惑。 I've read Mozilla's documentation on textarea elements, and I believe my call to setSelectionRange is valid.我已经阅读了Mozilla 关于 textarea 元素的文档,我相信我对 setSelectionRange 的调用是有效的。 Could this somehow be related to the fact that I have created the textarea programmatically and that it is not actually being displayed?这是否与我以编程方式创建文本区域并且实际上并未显示这一事实有关?

Found the answer to this as I was typing the question, so I figured I would share for anyone who may stumble upon this.当我输入问题时找到了这个问题的答案,所以我想我会分享给任何可能偶然发现这个问题的人。 The answer was obvious, I basically hit upon in my last sentence: I was creating a textarea DOM element with $('') and storing that object, but I never inserted that object into the document.答案很明显,我基本上是在最后一句话中想到的:我正在用 $('') 创建一个 textarea DOM 元素并存储 object,但我从未将 object 插入到文档中。 After I appended the element to the body, setSelectionRange updates the selection as expected.在我将元素附加到正文后,setSelectionRange 按预期更新选择。 In my situation, it isn't really desirable to display the actual textarea on my unit test results page, but this is easily fixed with a call to $textarea.hide().在我的情况下,在我的单元测试结果页面上显示实际的文本区域并不是真正可取的,但这可以通过调用 $textarea.hide() 轻松解决。

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

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