2011-09-12 6 views
2

を働いていないいくつかの単語を検索から渡すラップを外し、私はその後div、一つのリンクをクリックして、外側wrapを削除しますが、私のコードはwrapunwrapのために働いていないでそれらをラップします。どこが間違っていますか?ありがとう。jqueryのワード縦糸と

<?php $_GET['search']='this is a text'; ?> 
<script type="text/javascript" src="../jquery.js" ></script> 
<script> 
$(document).ready(function() { 
    var words = '<?php echo $_GET['search']; ?>'; 
    $(words).wrap('<div id="words" />'); 
    $('body').append(words); 
    $('#click').click(function(){ 
     $(words).unwrap('<div id="words" />'); 
    }); 
}); 
</script> 
<body> 
<a id="click">remove me</a> 
</body> 

答えて

2

言葉はラップのみjQueryオブジェクト、またはDOM要素上で動作列は使用できない文字列でなければなりません。

はこのような何かを試してみてください。

<script> 
$(document).ready(function() { 
    var words = 'this is your search string'; 
    words = '<div id="words">'+words+'</div>'; // wrap it, basically creating the string 
    $('body').append(words); 
    $('#click').click(function(){ 
     $('#words').replaceWith($('#words').get(0).childNodes); // get the words outsde of it again, unwrap only works on the inner element. 
    }); 
}); 
</script> 
<body> 
    <a id="click">remove me</a> 
</body> 
0

wordsセレクタ、ない

0

あなたは、ドキュメントに追加する前に要素をラップし、言葉はDOM要素でなければなりません。

$('body').append()<div id="words">your_php_result</div>に直接入力してみてください。

0

これは機能しないセレクタです。あなたは、このような構造でtext要素を検索します$('this is a text')を、やって終わる:

<this> 
    <is> 
    <a> 
     <text></text> 
    </a> 
    </is> 
</this> 

もちろんそこには、このような要素がないので、結果は空のjQueryオブジェクトです。

単語を単語に囲みたい場合は、ページ上のすべての関連要素をループし、.text()または.html()を使用して内容を取得し、テキスト内の単語を見つけ、それらを囲むHTMLコードで置き換えます。単語を入力し、テキストを要素に戻します。

一般的に、これはサーバー側のコードで行う方が簡単で堅牢です。

2

ポイント1 -

ポイント2上記のようにあなたは、唯一のDOM要素をラップすることができます - あなたがラップする前に、あなたがDOMに追加する必要があり、そうでない場合は追加「DIV」へのアクセス 何もありませんよ

ポイント3 - $(単語)と$(単語)を2回書くと、これらは同じオブジェクトではありません!

あなたのような何か実行する必要があります。また、チェック

$(document).ready(function() { 
    var words = $('<span></span>').text('words words words'); 
    words.wrap('<div id="words"></div>'); 
    $('body').append(words); 
    $('#click').click(function(){ 
     words.unwrap('<div id="words" />'); 
    }); 
}); 

this link to jsFiddle