简体   繁体   English

jQuery突出显示除href值之外的单词

[英]jQuery Highlight Words Except Value of href

This answer works almost perfectly for my needs. 这个答案几乎完全符合我的需求。 The problem is that it will also match URL values in the href attribute of an a tag. 问题是它还将匹配标签的href属性中的URL值。 So If I have: 所以,如果我有:

<a href="/a-link-to-a-porsche-page">This is a link to a porsche page</a>

and use this selector: 并使用此选择器:

$("a").highlight("porsche", "highlighted");

porsche gets matched in both the url and the link text. 保时捷在网址和链接文字中都匹配。 What can be done so that values of the href attribute are omitted? 可以做什么,以便省略href属性的值?

Previously referenced answer for posterity: 以前参考的后代答案:

jQuery.fn.highlight = function (str, className) {
    var regex = new RegExp(str, "gi");

    return this.each(function () {
        this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
    });
};

Didn't know about jsfiddle. 不知道jsfiddle。 Here's a more complete example based on justkt's response: http://jsfiddle.net/Dzejms/L5Knh/1/ 这是一个基于justkt响应的更完整的例子: http//jsfiddle.net/Dzejms/L5Knh/1/

------edit------ - - - 编辑 - - -

a cursory search on google turned up this neat jquery plugin . 谷歌粗略搜索了这个整洁的jquery插件 the idea is the same as what is the other answer, but it uses recursion and regex to make it more efficient. 这个想法与其他答案相同,但它使用递归和正则表达式来提高效率。 check it out. 看看这个。

One option is to drill down to the children of each object to make sure that you aren't grabbing the DOM nodes in your innerHTML. 一种选择是向下钻取每个对象的子节点,以确保您没有抓住innerHTML中的DOM节点。

Here is a fairly inefficient example that uses recursion on the children of each matched object: 这是一个相当低效的示例,它在每个匹配对象的子节点上使用递归:

jQuery.fn.highlight = function (str, className) {
    var regex = new RegExp(str, "gi");

    return this.each(function () {
        checkHighlight(this);
    });

    function checkHighlight(obj) {
        var children = $(obj).children();
        if(children.length == 0) {
            doHighlight(obj);
        } else {
            children.each(function() {
                checkHighlight(this);
            });
        }
    }

    function doHighlight(obj) {
        obj.innerHTML = obj.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
    }
};

See it in action here . 这里看到它。

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

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