一些单词从搜索传递,我想用div
包装然后单击一个链接,删除外部wrap
,但我的代码不适用于wrap
和unwrap
。怎么了?
<?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>
单词不能是一个字符串换行只适用于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>
第1点 - 您可以只包装DOM元素,如上所述
第2点 - 在你换行之前,你必须将它添加到DOM中,否则将无法访问添加的'div'
第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" />');
});
});
words
必须是选择器,而不是字符串
在将元素添加到文档之前包装元素,并且单词必须是DOM元素。
您可以尝试直接在$('body').append()
上使用<div id="words">your_php_result</div>
。
这是你的选择器不起作用。你最终做了$('this is a text')
,它会在这样的结构中搜索text
元素:
<this>
<is>
<a>
<text></text>
</a>
</is>
</this>
当然没有这样的元素,所以结果是一个空的jQuery对象。
如果你想在文本中包装单词,你必须遍历页面上的所有相关元素,使用.text()
或.html()
获取它们的内容,在文本中找到单词并用包装单词的HTML代码替换它们,然后放入文本回到元素中。
通常,这在服务器端代码中更容易且更健壮。