javascript - 检查所选文本是否在给定的 CSS 类中?

标签 javascript jquery html css

当用户选择文本时,我需要在执行最终任务之前检查两件事:

  • 所选文本是否在主 .entry-content div 中? 我已经做到了。
  • 所选文本是否在任何突出显示 css 类之外或疯狂? 我需要帮助。

基本上:

  • 如果选择“他早熟”,则返回false
  • 如果选择“第一南非 bool bool 俱乐部的负责人”,则返回真

HTML 源代码:

<p>
    <span id="subject-47" class="subject highlighted">Semencic credits his early familiarity with the breed to his own travels to South Africa<span class="count">4</span></span>, but especially to his frequent correspondence with the head of the first South African Boerboel club, one Mr. Kobus Rust. <strong>The Boerboel Breeders Association was established in 1983</strong> in the Senekal district of the Free State with the sole objective of ennobling and promoting the Boerboel as a unique South African dog breed.
</p>

我当前的 Javascript(工作但我需要最后一个检查功能)

$( window ).load(function() {

    $(document.body).bind('mouseup', function(e){

        snapSelectionToWord();
        var txt = getHTMLOfSelection();
        var contentPos = $('.entry-content').html().indexOf( txt );

        if( contentPos > 0 ) {
            // do my thing here
            // after I check txt IS NOT within a .highlighted css class
        }

    });

});

最佳答案

我设法按照我的意愿构建了一个函数。

function isTextInClass( text, css_class ) {

    var result = false;

    $( '.highlighted' ).each( function( index ) {

        if( $( this ).html().indexOf( text ) != 'undefined' ) {

            var foundAt;

            foundAt = $( this ).html().indexOf( text );

            if( foundAt > 0 ) {
                result = true;
            }

        }

    });

    return result;

}

关于javascript - 检查所选文本是否在给定的 CSS 类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37002847/

相关文章:

javascript - 拖动 div 正在创建更多 div

javascript - 从 url 中删除最后一个参数

javascript - Jquery 倒计时在 Safari 中显示 NaN,在 Chrome/Firefox 中工作正常

javascript - 数组中的 jQuery 随机项不起作用

javascript - 是什么导致了这个 JS 控制台错误?

jquery - 修复了比内容长的 div - 如何让内容粘在屏幕底部?

javascript - 通过 ID 获取动态创建的元素 (Jquery)

javascript - 使用 jQuery slideToggle 在主列表下方扩展水平嵌套列表?

javascript - 如何在页面加载时显示隐藏的列表项?

javascript - 如何使 <li> 在重定向到新页面时保持突出显示?