使用jQuery在注释标签之间选择文本 [英] Selecting text between comment tags with jquery
问题描述
尝试了几种方法,使两个Text内容在注释块之间具有不同的类名.
Tried several methods to give the two Text content different class names that is between the comment blocks.
<a>
<!--:en-->Text1<!--:-->
<!--:fr-->Text2<!--:-->
</a>
我发现最接近的解决方案是 Jquery Next Adjacent Selector ,并尝试使用 jQuery('prev + next')函数,但所有示例均针对html元素之类;
The closest solution that I found is I think, Jquery Next Adjacent Selector and tried to use jQuery('prev + next') function but all the examples are targeting html elements like;
$("label + input").addClass("classone");
我只是找不到选择注释块后面的文本的方法.
I just couldn't find a way to Select the text that comes after comment blocks.
推荐答案
我不确定速度有多快,但是您可以让它检查正文中的所有代码并替换那些预定义的类.如果您对诸如<a>
的特定标签感兴趣,那么可能会更快.这就是我的方法.
I'm not sure how fast that would be but you can make it check all the code in the body and replace those predefined classes. If you're interested in a specific tag such as <a>
that might be even faster. This would be my approach.
var classes = {en:'classEN',fr:'classFR'};
// predefined class pairs
$('body').children().each(function() {
var html = $(this).html();
// grabs all the html code. then finds and replaces:
html = html.replace(/<!--\s*:(\w+)(.*?)-->(.*?)<!--\s*:\s*-->/gi, function() {
var lang = arguments[1].toLowerCase();
// this catches the first parenthesized group that consists
// of letters (after the colon) and converts it into lowercase
if (!classes[lang]) return arguments[0];
// returns the original if no match if found in the classes object
var comment = '';
if (!/^\s*$/.test(arguments[2])) comment = '<!--' + arguments[2] + '-->';
// if you have a comment like <!--:en This is English-->
// it keeps the comment as <!-- This is English --> and...
return comment + '<span class="' + classes[lang] + '">' + arguments[3] + '</span>';
// returns the result
});
$(this).html(html);
// finally reassigns the modified result to each child
});
这篇关于使用jQuery在注释标签之间选择文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!