7

だから私はこのようなHTMLの一部を持っています...

<p>This is some copy. In this copy is the word hello</p>

jquery を使用して、hello という単語をリンクに変換したいと考えています。

<p>This is some copy. In this copy is the word <a href="">hello</a></p>

それ自体はさほど難しいことではありません。私の問題は、単語が既に以下の例のようにリンクの一部になっている場合です...

<p>In this copy is the <a href="">word hello</a></p>

リンク内のリンクで終わってほしくありません...

<p>In this copy is the <a href="">word <a href="">hello</a></a></p>

どんな助けでも大歓迎です。

4

9 に答える 9

3

少しの正規表現でうまくいくはずです(更新、以下を参照):

$(document).ready(function(){
    var needle = 'hello';
    $('p').each(function(){
        var me = $(this),
            txt = me.html(),
            found = me.find(needle).length;
        if (found != -1) {
            txt = txt.replace(/(hello)(?!.*?<\/a>)/gi, '<a href="">$1</a>');
            me.html(txt);
        }
    });
});

フィドル: http://jsfiddle.net/G8rKw/

編集:このバージョンはよりうまく機能します:

$(document).ready(function() {
    var needle = 'hello';
    $('p').each(function() {
        var me = $(this),
            txt = me.html(),
            found = me.find(needle).length;
        if (found != -1) {
            txt = txt.replace(/(hello)(?![^(<a.*?>).]*?<\/a>)/gi, '<a href="">$1</a>');
            me.html(txt);
        }
    });
});

フィドル: http://jsfiddle.net/G8rKw/3/

もう一度編集: 今回は、「hello」が変数として正規表現に渡されます

$(document).ready(function() {
    var needle = 'hello';
    $('p').each(function() {
        var me = $(this),
        txt = me.html(),
        found = me.find(needle).length,
        regex = new RegExp('(' + needle + ')(?![^(<a.*?>).]*?<\/a>)','gi');
        if (found != -1) {
            txt = txt.replace(regex, '<a href="">$1</a>');
            me.html(txt);
        }
    });
});

フィドル: http://jsfiddle.net/webrocker/MtM3s/

于 2012-10-10T16:47:30.543 に答える
1

このようにできます。

ライブデモ

$('p').each(function(){    
    if($(this).find('a').length > 0) return;  
    lastSpaceIndex = $(this).text().lastIndexOf(' ');
    if(lastSpaceIndex  == -1)
        lastSpaceIndex = 0;    
    WordToReplace = $(this).text().substring(lastSpaceIndex);
    idx = $(this).text().lastIndexOf(WordToReplace);
    resultstring = $(this).text().substring(0, idx); 
    $(this).html(resultstring);
    $(this).append($( "<a href='#'>" + WordToReplace  + "</a>"));
});​
于 2012-10-10T14:23:19.397 に答える
1

この jQuery ソリューションは、特定の用語を検索し、リンク終了タグが後に続いていることがわかった場合、リンクを作成しません。

var searchTerm = "hello";

$('p:contains("' + searchTerm + '")').each(function(){
    var searchString = $(this).html();
    var searchIndex = searchString.indexOf(searchTerm);
    var startString = searchString.substr(0 , searchIndex);
    var endString = searchString.substr(searchIndex + searchTerm.length);
    if(endString.match(/<\/a>/g)) return;
    $(this).html(startString + "<a href=''>" + searchTerm + "</a>" + endString);
});​

これはjsfiddleへのリンクです。

于 2012-10-10T15:32:46.910 に答える
1

置換テキストがリンクタグで囲まれているかどうかを確認する簡単な関数を作成しました。下記参照、

デモ: http://jsfiddle.net/wyUYb/4/

function changeToLink (sel, txt) {
   var regEx = new RegExp(txt, 'g');
   $.each($(sel), function (i, el) {
       var linkHTML = $(el).html();
       var idx = linkHTML.indexOf(txt);

       if (idx >= 0) {
           var t = linkHTML.substring(idx);
           //Fix for IE returning tag names in upper case http://stackoverflow.com/questions/2873326/convert-html-tag-to-lowercase
           t = t.replace(/<\/?[A-Z]+.*?>/g, function (m) { return m.toLowerCase(); })
           var closingA = t.indexOf('</a>');

           t = t.substring(0, closingA);
           if (closingA != -1) {
               t = t.substring(0, closingA); 
               if (t.indexOf('<a') < txt.length) {
                   return;
               }
           }               

           linkHTML = linkHTML.replace(regEx, '<a href="">' + txt + '</a>');
           $(el).html(linkHTML);
       }           
   });
}

また、ネストされたリンクを追加したとしても、ブラウザはそれを 2 つのリンクに変更するだけです。ネストされたリンクを使用することが違法である可能性があります。下記参照、

ネストされたリンクについては W3C にも記載されています

12.2.2 ネストされたリンクは違法です

A 要素で定義されたリンクとアンカーはネストできません。A 要素には、他の A 要素を含めることはできません。

DTD では LINK 要素が空であると定義されているため、LINK 要素をネストすることもできません。

そのため、ブラウザはネストされたリンクを個別のリンクとして扱います。

http://jsfiddle.net/H44jE/

画像の右下にある firebug inspect を参照してください。

ここに画像の説明を入力

于 2012-10-10T15:32:48.753 に答える
0

リンクに変換する前に、単語の親要素をテストできませんか?

if (parent != 'a') {
   // do your thing
}

(これをテストするための実際のjQueryが何であるかはわかりません)

編集

<p>以下は、リンクを含まないすべての要素の単語を置き換えます。

必要に応じて正確に機能しない可能性がありますが、うまくいけば方向を示します

// get all p elements that contain the word hello but DO NOT have link in them
var elems = $('p:contains("hello")').not(':has(a)');


// replace instances of hello in the selected p elements
$(elems).html($(elems).html().replace(/(hello)/g,'<a href="new">$1</a>'));

JSBinのライブデモ

于 2012-10-10T14:07:56.163 に答える
0

次のような.replacejquery関数を使用してみてください。

var str = $('p').html().replace('(some)','(to some)');
于 2012-10-10T14:08:35.727 に答える
0

最初に、現在のアンカー タグを取り除く間、単語を保持します (存在する場合):

$('a').each(function() {
    $(this).replaceWith(this.childNodes);
 });

次に、作業する必要がある文字列を置換します

$('p').html($('p').text().replace('hello', '<a href="">hello</a>'));
于 2012-10-10T15:12:13.323 に答える
0

jquery :not セレクターまたは .not() が必要です。

API ドキュメントはこれをうまくカバーしています。コンテンツを選択してから、その中のリンクを選択解除できるはずです。

http://api.jquery.com/not-selector/

于 2012-10-10T14:21:05.210 に答える
0

単語を検索してその親を見つけようとする代わりに、リンクを検索して、含まれている単語を確認します。

if($('a').text() === "hello"){
  //already linked
}else{
  //not linked
}
于 2012-10-10T14:24:44.533 に答える