javascript - 为什么 javascript crashToStart() 会抛出错误

标签 javascript select

我正在运行这段代码,用于在用户选择 iframe 之外的另一个单词时取消选择用户在 iframe 中选择的单词:

function getCurrentWord() {
    var range;
    var w = "";

    if (document.selection) {
        ////IE
        range = document.selection.createRange();
        w = trim(range.text);
    } else {
        ////NOTIE
        w = trim(window.getSelection().toString());
    }

    if (w != "" && document.getElementById("frmBook")) {
        var oTextRange;
        if (document.selection) {
            ////IE
            oTextRange = document.getElementById("frmBook").contentWindow.document.selection.createRange();
            oTextRange.expand("word");
            oTextRange.execCommand("unselect") ;
        } else {
            ////NOTIE       
            oTextRange = document.getElementById("frmBook").contentWindow.getSelection();
            oTextRange.collapseToStart();
        }
    }

    if (w == "" && document.getElementById("frmBook")) {
        if (document.selection) {
            ////IE
            range = document.getElementById("frmBook").contentWindow.document.selection.createRange();
            w = trim(range.text);
        } else {
            ////NOTIE
            w = trim(document.getElementById("frmBook").contentWindow.getSelection().toString());
            /*
            IF I PUT IT HERE IT DOESN'T SHOW AN ERROR
            oTextRange = document.getElementById("frmBook").contentWindow.getSelection();
            oTextRange.collapseToStart();
            */
        }
    }
    return w;
}

问题是我在 Firefox 错误控制台上收到此错误:

Timestamp: 9/5/2012 12:20:42 μμ Error: uncaught exception: [Exception... "An attempt was made to use an object that is not, or is no longer, usable" code: "11" nsresult: "0x8053000b (NS_ERROR_DOM_INVALID_STATE_ERR)" location: "http://192.168.0.88/test.js Line: 295"]

当代码位于

时会发生该错误
oTextRange.collapseToStart();

线。

我尝试像这样在一行中运行它:

document.getElementById("frmBook").contentWindow.getSelection().collapseToStart();

但我遇到了同样的错误

frmBook是iframe的ID

如果我运行那段导致错误的代码(我已将其注释掉),它不会显示错误,这很奇怪!

有人知道我做错了什么吗? 提前致谢

最佳答案

查看源代码(可能是旧版本)http://dxr.lanedo.com/mozilla-central/layout/generic/nsSelection.cpp.html如果实际上没有选择任何内容,那么 collapseToStart 似乎会产生该错误。您可以检查 oTextRange.rangeCount 是否 < 1,如果是,则不进行折叠。 (如果有某种原因导致这不可能,那么您可能会遇到不同的问题。)

关于javascript - 为什么 javascript crashToStart() 会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10513391/

相关文章:

javascript - 使用条件渲染时出现警告 : Functions are not valid as a React child,

javascript - Hook 到网页的 window.onload 的更干净的方法?

javascript - 带有对象数组的多重选择和 v-model

javascript - 使用 Jquery 在动态输入中添加值

javascript - 设置 Chrome 窗口的页面标题.open

javascript - javascript本地存储会传播给同一台Windows 7 PC上的其他用户吗?

MySQL 选择一组列作为一个别名

mysql - 如何从sql语句中选择准确的值

php - 在 mysql/php 中选择列名

php - 如何更改select标签中下拉列表的背景颜色?