javascript - jQuery 可以处理不在 DOM 中的 html 字符串吗?

标签 javascript jquery

我有一个用模板创建的 html 字符串。

这个字符串有一个带有一堆行的 html 表,我想使用 jquery 来操作这个字符串,例如根据逻辑或其他操作向某些行添加一些类,然后让 jquery 返回一个字符串。但是,jQuery 似乎只操作 DOM。但我还不想将此字符串发布到 DOM 中。

var origString = "<table><tr id='bla'>...more html inside here...</tr></table>";
//Something like
var newString = $(htmlString -> '#bla').addClass('blaClass');
// this syntax is obviously wrong, but what I mean is I'm trying 
// to look inside the string not the dom

或者最好先将这个字符串发布到一个不可见的 div 中,然后再用 jquery 对其进行操作?

最佳答案

将它解析为一个变量,操作,然后追加:

var origString = "<table><tr id='bla'>...";
origString = $.parseHTML(origString);
$(origString).find("tr").addClass("test");
$("body").append(origString);

概念演示:http://jsfiddle.net/6bkUv/

关于javascript - jQuery 可以处理不在 DOM 中的 html 字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24663360/

相关文章:

jquery - 如何使用 jQuery 访问这些奇怪的 JSON 项?

jquery - Angular mouseenter 在 Chrome 中不起作用

javascript - 图像淡入淡出,间隔困惑

java - 适用于 Android 的 Phonegap jabber 插件

javascript - 编写 AJAX 来接收 JSON 文件?

javascript - google Oauth 登录 https 服务器

jquery - 如何在 CodeIgniter 中包含 jQuery 文件?

javascript - knockout 错误 : You cannot apply bindings multiple times to the same element

javascript - 从 onClick 传递值

Javascript:检查服务器是否在线?