简体   繁体   English

带有javascript函数的HTML短语标记

[英]HTML phrase markup with javascript function

I'm looking the way to markup a phrase in an html with a javascript function. 我正在寻找一种使用javascript函数标记html中的短语的方法。 The thing is, I have a HTML page with a lot of words but I need to markup the phrase every time that appear. 关键是,我有一个包含很多单词的HTML页面,但是每次出现时我都需要标记该短语。 Does anyone has any idea how to do this? 有谁知道如何做到这一点?

You can find with keyword like html replace or something which will be well suited to your situation. 您可以找到诸如html replace之类的关键字,或者更适合您情况的关键字。

By using gulp, there is gulp-html-replace module ( https://www.npmjs.com/package/gulp-html-replace ) 通过使用gulp,有gulp-html-replace模块( https://www.npmjs.com/package/gulp-html-replace

Assuming that all your text is within p-tags, you can select all paragraphs by 假设您所有的文字都在p标签内,则可以按以下方式选择所有段落

var allP = document.getElementsByTagName("P")

Then loop over allP and get the html of the tag. 然后遍历allP并获取标记的html。

for (var i; i< allP.length; i++) {
    var thisP = allP[i];
    var htmlP = thisP.innerHTML;
}

Then you can split htmlP with your phrase (in the for loop), eg: 然后,您可以使用短语(在for循环中)拆分htmlP,例如:

var partsP = htmlP.split("I want to be highlighted");

And den rebuilt your html: 和den重建您的html:

var newHtmlP = "";
for (var j; j < partsP.length; j++) {
    newHtmlP = newHtmlP + partsP[j] + '<span style="color:red">I want to be highlithed</span>';
}

You have to make sure, that the phrase is not appended one time to much at the end (I did not implement this here). 您必须确保,该短语最后不会一次添加过多(我在这里没有实现)。 Finally you set the inner html: 最后,您设置内部html:

thisP.innerHTML = newHtmlP;

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

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