【问题标题】:How do I copy an HTML document and edit the copy based upon the selection, without altering the original document?如何在不更改原始文档的情况下复制 HTML 文档并根据选择编辑副本?
【发布时间】:2015-05-18 22:09:21
【问题描述】:

我有一个 HTML 文档,我想根据标签是否在当前选择范围内,使用 Javascript 动态删除其中的一些标签。但是,我不想更新页面上的实际文档,我想复制整个页面的 HTML 并编辑该副本。问题是我从selection.getRangeAt(0) 得到的Range 对象仍然指向原始文档,据我所知。

我已经设法使用此代码编辑原始文档:

var node = window.getSelection().getRangeAt(0).commonAncestorContainer;
var allWithinRangeOfParent = node.getElementsByTagName("*");

for (var i=0, el; el = allWithinRangeParent[i]; i++) {
    // The second parameter says to include the element 
    // even if it's not fully selected
    if (selection.containsNode(el, true) ) {
        el.remove();
    }
 }

但我想做的是以某种方式执行与删除元素相同的操作,但将它们从原始 HTML 的 副本 中删除。我做了这样的副本:var fullDocument = $('html').clone();我怎么能做到这一点?

【问题讨论】:

    标签: javascript html dom range selection


    【解决方案1】:

    在克隆之前动态地为加载的所有元素添加类或数据属性,以便您有一个参考点,然后在共同祖先上获取类或数据属性并将其从克隆中删除。如果你愿意,我可以举个例子吗?按照这些思路 - http://jsfiddle.net/9s9hpc2v/ 工作不正常,但你明白了要点。

    $('*').each(function(i){
        $(this).attr('data-uniqueId', i);
    });
    var theclone = $('#foo').clone();
    
    
    function laa(){
        var node = window.getSelection().getRangeAt(0).commonAncestorContainer;
        if(node.getElementsByTagName){
    
        var allWithinRangeOfParent =  $(node).find('*');
            console.log(allWithinRangeOfParent, $(allWithinRangeOfParent).attr('data-uniqueId'));
            $.each(allWithinRangeOfParent, function(){
                theclone.find('[data-uniqueId="'+$(this).attr('data-uniqueId')+'"]').remove();
            });
            console.log(theclone.html());
        }
    }
    $('button').click(laa);
    

    【讨论】:

      猜你喜欢
      • 2021-09-16
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      相关资源
      最近更新 更多