如何使用jQuery为特定单词的所有实例的/ parts /设置样式?

异常情况。我有一个客户,我们称他们为“立即购买”。他们想为他们的名字的每个实例在其整个网站的副本,以程式化的类似“购买现在 ”,其中他们的名字下半年为黑体。

我真的很讨厌花一天时间在所有副本中添加<strong>标签。有没有使用jQuery的好方法?

我已经看到了jQuery的Highlight插件,它非常接近,但是我只需要将该单词的后半部分加粗即可。


繁星点点滴滴
浏览 478回答 3
3回答

幕布斯6054654

正则表达式和replace()思想。就像是var text = $([selector]).html();text = text.replace(/Now/g,'<strong>Now<\strong>');$([selector]).html(text);使用html()此操作时要小心。首先,有可能替换元素href属性中的匹配字符串<a>以及其他可能导致页面无法正常运行的属性。可能可以编写更好的正则表达式来克服某些潜在的问题,但是性能可能会受到影响(我不是正则表达式专家)。其次,html()用于替换内容将导致不可序列化的数据(例如绑定到要替换的元素标记的事件处理程序,表单数据等)丢失。编写仅针对文本节点的函数可能是更好/更安全的选择,这仅取决于页面的复杂程度。如果您有权访问HMTL文件,则如果内容是静态的,则最好查找并替换要更改文件外观的单词。在大多数情况下,NotePad ++的 “ 在文件中查找”选项可以胜任此工作。与SingleShot的建议一起使用并<span>与CSS类一起使用将比使用<strong>元素提供更多的灵活性。

江户川乱折腾

var Run=Run || {};Run.makestrong= function(hoo, Rx){&nbsp;if(hoo.data){&nbsp; var X= document.createElement('strong');&nbsp; X.style.color= 'red'; // testing only, easier to spot changes&nbsp; var pa= hoo.parentNode;&nbsp; var res, el, tem;&nbsp; var str= hoo.data;&nbsp; while(str && (res= Rx.exec(str))!= null){&nbsp; &nbsp;var tem= res[1];&nbsp; &nbsp;el= X.cloneNode(true);&nbsp; &nbsp;el.appendChild(document.createTextNode(tem));&nbsp; &nbsp;hoo.replaceData(res.index, tem.length,'');&nbsp; &nbsp;hoo= hoo.splitText(res.index);&nbsp; &nbsp;str= hoo.data;&nbsp; &nbsp;if(str) pa.insertBefore(el, hoo);&nbsp; &nbsp;else{&nbsp; &nbsp; pa.appendChild(el);&nbsp; &nbsp; return;&nbsp; &nbsp;}&nbsp; }&nbsp;}}Run.godeep= function(hoo, fun, arg){&nbsp;var A= [];&nbsp;if(hoo){&nbsp; hoo= hoo.firstChild;&nbsp; while(hoo!= null){&nbsp; &nbsp;if(hoo.nodeType== 3){&nbsp; &nbsp; if(hoo.data) A[A.length]= fun(hoo, arg);&nbsp; &nbsp;}&nbsp; &nbsp;else A= A.concat(arguments.callee(hoo, fun, arg));&nbsp; &nbsp;hoo= hoo.nextSibling;&nbsp; }&nbsp;}&nbsp;return A;}//test**Run.godeep(document.body, Run.makestrong,/([Ee]+)/g);**
打开App,查看更多内容
随时随地看视频慕课网APP