使用javascript在静态HTML页面上突出显示给定字符串 [英] Highlight given strings on a static HTML page with javascript

查看:84
本文介绍了使用javascript在静态HTML页面上突出显示给定字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个静态HTML文件:

There is a static HTML file:

<html>
<body>
ABC
XYZ
foo
bar
</body>
</html>

我们的问题:如何输入按钮/链接(?)到这个单一的静态HTML文件,以便访问此页面的人可以在点击页面上的按钮/链接后突出显示给定预定的字符串?用javascript?但是怎么样?

Our question: How can I put in buttons/links (?) to this single, static HTML file, so that the people that are visiting this page can highlight given predetermined strings after clicking on the button/link on the page? With javascript? But how?

更新:将上述HTML中的ABC放入< big>< b> 标签中,如:
< big>< b> ABC< / b>< / big>

UPDATE: Place "ABC" from the above HTML into <big><b> tags like: <big><b>ABC</b></big>

推荐答案

有几种方法可以做到这一点。

There are several ways you could do this.

1-有一个变量,其中包含你想要突出显示的字符串。

1- Have a variable with the strings you want highlighted.

highlight = ['ABC', 'XYZ', ... ];

2-制作突出突出显示字符串的函数变量

makeHL = function(strings) {
    // Get the HTML you want to search and replace strings on
    myHTML = document.getElementsByTagName('body')[0].innerHTML;

    // Use string.replace to add <b></b> to them or another form of highlighting. 
    // You can use regular expressions here to make it more reliable.
    strings.forEach(function(str) {
        myHTML = myHTML.replace(str, '<b>' + str + '</b>');
    });

    // Reinsert your new html with the strings highlighted.
    document.getElementsByTagName('body')[0].innerHTML = myHTML
}

3-当用户点击您的链接或按钮时,只需拨打 makeHL(突出显示)

3- When the user clicks your link or your button, just call makeHL(highlights)

确保包含Ecmascript5垫片例如 es5-shim 使用 .forEach()在不支持它的浏览器中。

Make sure that you include a Ecmascript5 shim such as es5-shim for use of .forEach() in browsers that don't support it.

1-包含 jQuery

<script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>

2-为您的替换品添加变量:

2- Have a variable with your replacements:

highlight = ['ABC', 'XYZ', ... ];

3-制作突出突出显示字符串的函数变量并将其绑定到点击事件:

3- Make the function that highlights the strings from the highlight variable and bind it to the click event:

$('.makeHL').on('click', function() {
    // Get the HTML you want to search and replace strings on
    myHTML = $('body').html();

    // Use string.replace to add <b></b> to them or another form of highlighting. 
    // You can use regular expressions here to make it more reliable.
    $.each(highlight, function(i, str) {
        myHTML = myHTML.replace(str, '<b>' + str + '</b>');
    });
    // Reinsert your new html with the strings highlighted.    
    $('body').html(myHTML);
});

这篇关于使用javascript在静态HTML页面上突出显示给定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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