Javascript jquery word扭曲和删除包裹未工作
有些单词从搜索中传递出去,我想用Javascript jquery word扭曲和删除包裹未工作,javascript,jquery,html,Javascript,Jquery,Html,有些单词从搜索中传递出去,我想用div将它们包装起来,然后单击一个链接,删除外部wrap,但我的代码不适用于wrap和unwrap。怎么了 <?php $_GET['search']='this is a text'; ?> <script type="text/javascript" src="../jquery.js" ></script> <script> $(document).ready(function() {
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>
$(文档).ready(函数(){
var-words='';
$(大写)。换行(“”);
$('body')。追加(文字);
$('#click')。单击(函数(){
美元(大写)。展开(“”);
});
});
把我带走
words必须是选择器,而不是字符串words不能是字符串换行符,只能用于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>
<this>
<is>
<a>
<text></text>
</a>
</is>
</this>
$(文档).ready(函数(){
var words='这是您的搜索字符串';
words=''+words+'';//包装它,基本上创建字符串
$('body')。追加(文字);
$('#click')。单击(函数(){
$(“#单词”).replaceWith($(“#单词”).get(0).childNodes);//再次将单词从其外部取出,展开仅对内部元素有效。
});
});
把我带走
在将元素添加到文档中之前,请先包装这些元素,Word必须是DOM元素
您可以尝试直接在您的php结果上使用
$('body').append()
。是您的选择器不起作用。最后执行$('thisatext')
,它将在如下结构中搜索text
元素:
<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>
<this>
<is>
<a>
<text></text>
</a>
</is>
</this>
当然没有这样的元素,所以结果是一个空的jQuery对象
如果要在文本中封装单词,必须循环浏览页面上的所有相关元素,使用.text()
或.html()
获取它们的内容,在文本中查找单词,并用封装单词的html代码替换它们,然后将文本放回元素中
一般来说,在服务器端代码中这样做更容易、更健壮。第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" />');
});
});
$(文档).ready(函数(){
var words=$('').text('words');
字。包装(“”);
$('body')。追加(文字);
$('#click')。单击(函数(){
字。展开(“”);
});
});
也检查