javascript - 替换jquery html对象中的类

标签 javascript jquery html

我一直在尝试使用 jquery 将函数应用于每个 html 标签,并在 html 对象(从文件导入)中包含某个类,但我无法让它工作。我浏览了 SE 上的其他几个问题,但找不到解决我的问题的方法。

在我的实际用例中,html 变量包含更多代码,但是这个

html = '<pre class = "classy"> text </pre>'
$(html).find('.classy').each( function (x) { 
    $('<pre class = "classy">' + '<h1>' + x + '<h1>' + '</pre>')
})

'<pre class = "classy"> text </pre>'

预期的输出更像

'<pre class = "classy"> <h1> text </h1> </pre>'

.replaceWith 也不起作用,所以我认为我在概念上做了一些错误的事情。有什么解决方案/提示吗?

最佳答案

尝试

var html = '<pre class = "classy"> text </pre>';
var a = $(html);
a.filter('.classy').each( function (i, x) { 
    $(x).wrapInner('<h1></h1>');
})

这里是变量a将具有预期内容 <pre class = "classy"> <h1> text </h1> </pre> .

演示:Fiddle

在给定值下,它甚至可以简化为

var a = $(html);
a.each( function (i, x) { 
    $(x).wrapInner('<h1></h1>');
})

演示:Fiddle

注意:如果您想要 a 的内容作为 html 字符串

var html = $('<div>').append(a.clone()).html();

演示:Fiddle

关于javascript - 替换jquery html对象中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15673223/

相关文章:

javascript - 如何向 Google pagespeed API 发送批量请求?

Jquery在DIV中的多个负载

javascript - MVC 4 根据 DropDownListFor 选择更改多个显示字段

javascript - 使用 jquery/javascript 在客户端格式化 html 数据

php - 为什么存储在 session 变量中的数组计数会加倍?

javascript - 从 paper.js 光栅导出 svg

javascript - 使用 jquery 在每一秒内重新加载一个 url

javascript - 使用 onclick 选项时,Ajax 无法使用 HTML 表单中的提交按钮

javascript - 匹配正则表达式模式仅计算单词列表中的唯一值

添加 ui-css 后,jQuery 不会在按钮单击时重新启用文本框