在追加之前如何修改html字符串中的元素 [英] How to modify the elements in an html string before appending

查看:91
本文介绍了在追加之前如何修改html字符串中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我在 https://stackoverflow.com/posts/20577488/中简化了我的问题 我省略了重要的中间步骤. 我想:

Maybe I oversimplified my question in https://stackoverflow.com/posts/20577488/ I left out an important intermediate step. I wanted to:

  • 创建一个Java脚本字符串x
  • 将x分配给jQuery对象(对吗?)
  • 在此对象上执行jQuery内容
  • 然后将其添加

  • create a Javascript string x
  • assign x to a jQuery object (right term?)
  • perform jQuery stuff on this object
  • then append it

var x = "<p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p> ";
var template = $(x);
template.find('p').attr('class','something');
template.appendTo( ".inner" );   

推荐答案

您需要使用filter而不是find.您要查找的是根级别的,因此您需要使用filter,因为find会查找根级别的p的后代.您也可以使用addClass添加一个类,除非您想删除现有的类.

You need to use filter instead of find. What you are looking for is at the root level so you need to use filter since find will look for descendants of p that are at the root level. Also you can use addClass to add a class unless you want to remove the existing classes.

var x = "<p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p>";
var template = $(x)
template.filter('p').attr('class','something');
//Or you can use 
//template.filter('p').addClass('something');
template.appendTo( ".inner" );  

演示

Demo

这篇关于在追加之前如何修改html字符串中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆