简体   繁体   English

获取所选文本javascript的span标签名称

[英]get the span tag name of selected text javascript

How to get the span name of selected text: 如何获取所选文本的跨度名称:

 <Span class='class1'> text2 text3 text4 text5 </span> text6

when user select text4 then I want to get Span=Class1 当用户选择text4时,我想得到Span = Class1

Any answer can help ( in Jquery or Rangy or ...) 任何答案都可以帮助(在Jquery或Rangy或...中)

This is a function which may help: 此功能可能会有所帮助:

function getSelectionParentElement() {
    var parentEl = null, sel;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            parentEl = sel.getRangeAt(0).commonAncestorContainer;
            if (parentEl.nodeType != 1) {
                parentEl = parentEl.parentNode;
            }
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        parentEl = sel.createRange().parentElement();
    }
    return parentEl;
}

It was taken from here Get parent element of a selected text , Author: Tim Down 它是从此处获取的。获取所选文本的父元素 ,作者:Tim Down

$('span').on('click', function(){
var classes = $(this).attr('class');
console.log(classes)   //if there are more than one class do classes.split(' ')
})

Extremely unedited fiddle https://jsfiddle.net/tvp0q761/ 极其未经编辑的小提琴https://jsfiddle.net/tvp0q761/

Here's a vanilla JS way of doing it. 这是一种普通的JS方法。 It assumes you'll have more than one span, hence querySelectorAll rather than querySelector . 它假定您将有一个以上的跨度,因此是querySelectorAll而不是querySelector

HTML HTML

<span class="class1"><p>text2</p><p>text3</p><p>text4</p></span>
<span class="class2"><p>text2</p><p>text3</p><p>text4</p></span>
<span class="class3"><p>text2</p><p>text3</p><p>text4</p></span>

JS JS

var spans = [].slice.call(document.querySelectorAll('span')).forEach(function (el) {
    el.onclick = showParentInfo;
});

function showParentInfo() {
    console.log(this.nodeName + '=' + this.className)   
}

DEMO DEMO

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

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