2011-09-12 4 views
2

일부 단어가 검색에서 전달되었으므로 div으로 묶어 외부 wrap을 제거하지만 내 코드는 wrapunwrap에서 작동하지 않습니다. 어디가 잘못 됐니? 감사.jquery word warp 및 wrap이 제거되지 않았습니다.

<?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

당신은 문서에 추가하기 전에 요소를 포장 단어는 DOM 요소해야합니다.

$('body').append()<div id="words">your_php_result</div>에 직접 입력 해보십시오.

0

선택자가 작동하지 않습니다. 물론

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

는 그런 요소가없는, 그래서 결과는 빈 jQuery를 개체입니다 :이 같은 구조에 text 요소를 검색 할, $('this is a text')을하고 끝낸다.

단어를 단어로 묶으려면 페이지의 모든 관련 요소를 반복하고 .text() 또는 .html()을 사용하여 콘텐츠를 가져와 텍스트에서 단어를 찾아서 해당 단어를 포함하는 HTML 코드로 대체해야합니다 단어를 입력하고 텍스트를 요소에 다시 넣습니다.

일반적으로 이것은 서버 측 코드에서보다 쉽고 강력합니다.

2

포인트 1 -

포인트 2 위에 언급 한대로, 단지 DOM 요소를 포장 할 수 없다 - 당신이 포장하기 전에, 당신이 DOM에 추가해야 추가 '사업부'로, 그렇지 않으면있을거야, 접근 을

포인트 3 - $ (단어)와 $ (단어)를 두 번 쓰면이 둘은 같은 대상이 아닙니다!

당신은 같은 것을 수행해야합니다 또한 확인

$(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

관련 문제