Javascript 使用html()编辑标题标记的jQuery问题
基本上,我在一个网站上有大量的H1H2和H3标签,我希望能够在这些标题标签的部分周围放置一个Javascript 使用html()编辑标题标记的jQuery问题,javascript,jquery,Javascript,Jquery,基本上,我在一个网站上有大量的H1H2和H3标签,我希望能够在这些标题标签的部分周围放置一个span 目前,我有以下几点: jQuery(document).ready(function(){ // get all headings first jQuery('h1, h2, h3').each(function(){ // get the text var theHtml = jQ
span
目前,我有以下几点:
jQuery(document).ready(function(){
// get all headings first
jQuery('h1, h2, h3').each(function(){
// get the text
var theHtml = jQuery(this).html();
// split by spaces
var theWords = theHtml.split(" ");
// count the words
var wordCount = theWords.length;
var newHtml;
if(wordCount < 2){
// only one word
newHtml = theHtml;
}
else if(wordCount == 2){
// word count is 2...
newHtml = theWords[0]+" <span style='color: #000'>"+theWords[1]+"</span>";
}
else {
// add the first two words:
newHtml = theWords[0]+" "+theWords[1]+" <span style='color:#000'>";
// need to loop through the array now
for(var i = 2; i<wordCount; i++){
newHtml = newHtml+theWords[i];
if(i+1 < wordCount){
newHtml = newHtml+" ";
}
}
//end
newHtml = newHtml+"</span>";
}
jQuery(this).html(newHtml);
});
});
就像这样:
<h2 class="entry-title"><a href="#" title="Permalink to About the Registry" rel="bookmark"><div data-type="input" data-post_id="62" class="fee-field fee-filter-the_title">About the Registry</div></a></h2>
但是,如果没有以管理员身份登录,则div将消失。请使用jQuery功能删除任何特定H1、H2标记等中的所有文本。这些标记中的其他HTML将被忽略
但是,我不确定您将如何恢复所有内部HTML标记。您尝试过jQuery的功能吗?我认为它只在一行中完成了你想要的
$('h1, h2, h3').wrapInner('<span></span>');
$('h1,h2,h3')。wrapInner('');
嘿!很好的一个,我认为这是可能的正则表达式。我给你举了一个简单的例子,涵盖了a和div的大部分。所有不是真正意义上的空格(在标记中)都将替换为\uuuuuuuuuuuuuu
或--
等符号,这些符号随后将被更改回原来的位置。
看一看
编辑后发表评论
这对于您发布的示例h1和h2不起作用。这只是一个如何处理这个问题的想法。我希望这对你有帮助!祝你好运
评论2在我自己编辑之后;-)
它确实有效,我只是忘了添加不区分大小写和递归!只是还没完成。需要进行更多的检查,如
”
或“
等,我希望这将使您走上正确的轨道。如果您知道“内部”HTML元素中将包含什么类,您可以抓住它
var outer = $('.entry-title');
var html = html.find('.fee-field');
if(html === null){
html = outer;
}
// html will either be your `h` element or your inner most element.
导致问题的HTML是什么样子的?该函数的问题是(据我所知)它将所有文本都包装在里面,而如果你看到我的代码,我只希望第一个1或2后面的所有单词都用一个span包装。嘿……这太棒了!如果我使用text()的话,这让我想到了然后替换了html()中可以解决此问题的相关单词!:)谢谢您的帮助。替换()是关键!:)
theHtml = theHtml.replace(/[\s]+\</gi,'<');
theHtml = theHtml.replace(/\s+[\'\"]/gi,'___');
theHtml = theHtml.replace(/[\'\"]\s+/gi,'---');
theHtml = theHtml.replace(/a\s/gi,'a_');
theHtml = theHtml.replace(/div\s/gi,'div_');
newHtml = newHtml.replace(/___/gi,' "');
newHtml = newHtml.replace(/---/gi,'" ');
newHtml = newHtml.replace(/div_/gi,'div ');
newHtml = newHtml.replace(/a_/gi,'a ');
var outer = $('.entry-title');
var html = html.find('.fee-field');
if(html === null){
html = outer;
}
// html will either be your `h` element or your inner most element.