使用jQuery查找多个文本字符串并更改其样式 [英] Find multiple text strings with jQuery and change its style

查看:222
本文介绍了使用jQuery查找多个文本字符串并更改其样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从此 http://zazl.linuxpl.info/title/ 有任何想法吗?我根本不是jquery程序员.

I use iambriansreed code from this topic to bold some text and its works fine. But i want to find multiple words like BMW, Mini Cooper etc in all title ID's on the same page and its not working. Here is example http://zazl.linuxpl.info/title/ Any ideas? Im not jquery programmer at all.

这是代码:

$(window).load(function() {
    // ADD BOLD ELEMENTS
    $('#titleh:contains("Mini Cooper")').each(function(){
        $(this).html( 
            $(this).html().replace(/Mini Cooper/g,'<span class="firstWord">$&</span>')
        );
    });

    $('#titleh:contains("BMW")').each(function(){
        $(this).html( 
            $(this).html().replace(/BMW/g,'<span class="firstWord">$&</span>')
        );
    });
});

我根据提到的 AlexKM 答案提出新问题/questions/9794851/find-text-string-in-jquery-and-make-it-bold/28559732#28559732>主题.

I ask new question in accordance with AlexKM answer in mentioned topic.

推荐答案

之所以不起作用,是因为您的文档中有多个具有相同ID的元素.因此,当您通过ID选择元素时,它只会选择具有该ID的第一个元素.

The reason it doesn’t work, is because you have multiple elements with the same ID in your document. So when you select an element by ID, it just selects the first element with that ID.

在HTML文档中,ID 必须是唯一的.请改用类:

In HTML documents, IDs must be unique. Use classes instead:

<span class="titleh">...</span>

针对您的JavaScript:

For your JavaScript:

$(window).on('load', function() {
    $('.titleh').each(function() {
        var $e = $(this),
            html = $e.html();

        html = html.replace(/Mini Cooper/g, '<span class="firstWord">$&</span>');
        html = html.replace(/BMW/g, '<span class="firstWord">$&</span>');
        /* Add more rules here */

        $e.html(html);
    });
});

这篇关于使用jQuery查找多个文本字符串并更改其样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆