javascript - 无法使用javascript到达DIV的节点内容

标签 javascript jquery html jquery-selectors contenteditable

当使 text-DIV 可编辑时,我使用 setEndOfContenteditable 函数将光标置于文本末尾。

//Insert cursor at end of contentEditable element
function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    { 
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}

当我以前只有一个 div,并且文本就在其内部时,这将完美地工作:

setEndOfContenteditable(curObj);

curObj 是其中包含文本的 DIV。

现在我已经切换到一种设计,其中仍然有 curObj -div,但仅作为框架,并且包含实际文本的 DIV 位于其中。通常我这样做是为了到达(选择)我的 jQuery 代码中的内部 div

var curObj = window.curObj;
var inner = '#' + $(curObj).attr("id") + ' .object_inner';
$(inner).doAllMyStuff;

但是这不适用于这个特定的 setEndOfContenteditable 函数,我得到的错误是

Uncaught Error: NotFoundError: DOM Exception 8 

以及 setEndOfContenteditable 函数第 7 行的错误点:

range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range

最佳答案

啊,我试图将 jQuery 选择器传递给普通的 javascript 函数(需要原始 DOM 元素)。这是一种解决方案,它获取原始 DOM 元素:

var spec = $(curObj).find('.object_inner');
setEndOfContenteditable(spec[0]);

特别感谢这个人: How to get a DOM Element from a JQuery Selector

关于javascript - 无法使用javascript到达DIV的节点内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19137570/

相关文章:

JavaScript、Jquery子节点迭代

javascript - 有条件地跳过提交的表单字段,减少 URL 困惑

c# - 无法在c#中获取Bootstrap所见即所得富文本编辑器的编辑器div的InnerHtml

javascript - 为什么我的 OpenLayers 3 map 没有显示在 Internet Explorer 11 中?

javascript - 弹出模式不会在 Safari 移动版中移动

javascript - SVG 旋转和缩放转换问题

javascript - grunt 未定义 - AngularJs

javascript - Android文件上传 - 文件名错误, native 浏览器

jquery - 根据调整大小和/或加载使用 jquery 移动对象

javascript - 尝试在其他类中实例化类时出错