使用jquery替换/操作html字符串中的元素 [英] Replacing / Manipulating element in html string using jquery

查看:904
本文介绍了使用jquery替换/操作html字符串中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html字符串(不是DOM),我想用jquery操作。为什么这不起作用:

I have a html string (not DOM), that I want to manipulate using jquery. Why doesn't this work:

var html = '<div><h4><a class="preview-target" href="content.html">Headline</a></h4></div>';
console.log(html);

var elem = $('h4', $(html));
// replace "Headline" with "whatever" => Doesn't work
elem.replaceWith("whatever");

console.log(html);

我有一个jsfiddle 这里进行测试。

I have a jsfiddle here for testing.

上面的代码只是一个简化的例子。真正的html要复杂得多,也就是说,我肯定需要依赖jQuery来操作html字符串。

The above code is just a simplified example. The real html is much more complex, that is, I definitely need to rely on jQuery for manipulating the html string.

推荐答案

你修改了jQuery对象,它不会改变字符串文字中的值。

When you modify the jQuery object, it will not change the value in the string literal.

你可以使用

var html = '<div><h4><a class="preview-target" href="content.html">Headline</a></h4></div>';
console.log(html);

var $html = $('<div />',{html:html});
// replace "Headline" with "whatever" => Doesn't work
$html.find('a').html("whatever");

console.log($html.html());

演示:小提琴

这篇关于使用jquery替换/操作html字符串中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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