计算选择中的节点数

时间:2013-09-10 09:15:13

标签: javascript jquery

如果我在浏览器上选择3或4行,那么我想要在浏览器上选择no,即选择计数<span>

我有一个example.html,其中包含以下代码,

<div id="p">
<p id="p1">
    <span>wefwef wefwefsdfc fcsdcs wefwscsdc qwefwcsdc </span>
    <span>wefwec acvsdc wecfsdc <br />asdcsdc sdcdc wedwed</span>
    <span> wefwec acvsdc wecfsdc asdcsdc sdcdc</span>
    <span> wefwec acvsdc wecfsdc<br /> asdcsdc sdcdc</span>
    <span>wefwec acvsdc wecfsdc asdcsdc sdcdc</span>
</p>
<p>
    <span>wefwef wefwefsdfc fcsdcs wefwscsdc qwefwcsdc </span>
    <span>wefwec acvsdc wecfsdc <br />asdcsdc sdcdc wedwed</span>
    <span> wefwec acvsdc wecfsdc asdcsdc sdcdc</span>
    <span> wefwec acvsdc wecfsdc<br /> asdcsdc sdcdc</span>
</p>
</div>

我有以下问题:

  1. 如何统计选定的<span>
  2. 我将如何选择<span>

1 个答案:

答案 0 :(得分:1)

您可以使用与此类似的代码获取选择的HTML:

function getSelectedHTML () {
    var result = '';
    var range;
    if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        result = range.htmlText;
    }
    else if (window.getSelection) {
        var selection = window.getSelection();
        if (selection.rangeCount > 0) {
            range = selection.getRangeAt(0);
            var clonedSelection = range.cloneContents();
            var div = document.createElement('div');
            div.appendChild(clonedSelection);
            result = div.innerHTML;
        }
    }

    return result;
}

之后,这是解析选择的问题。一种方法是使用jQuery:

var count = $('span', $(getSelectedHTML())).length;