2012-03-27 10 views
1

2つのテキストコンテンツにコメントブロックの間に異なるクラス名を付けるようにいくつかの方法を試しました。jqueryでコメントタグ間のテキストを選択

<a> 
<!--:en-->Text1<!--:--> 
<!--:fr-->Text2<!--:--> 
</a> 

Iが見つかった最も近い解決策は、私が考えるjqueryの次の隣接するセレクタあり、jQueryの(「PREV +次」)機能が、すべての実施例のようなHTML要素をターゲットにしているを使用することを試みました。

$("label + input").addClass("classone"); 

コメントブロックの後に続くテキストを選択する方法が見つかりませんでした。

答えて

1

最も簡単な方法は、this oneのようなコメントプラグインを使用することです。

1

私はどれほど速いのか分かりませんが、ボディのすべてのコードをチェックし、それらの定義済みのクラスを置き換えることができます。 <a>のような特定のタグに興味がある場合は、かもしれないがさらに高速になります。これは私のアプローチです。

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 
}); 
関連する問題