nac*_*all 20 javascript string jquery
我有一个html字符串(不是DOM),我想用jquery操作.为什么这不起作用:
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);
Run Code Online (Sandbox Code Playgroud)
我在这里有一个jsfiddle 进行测试.
上面的代码只是一个简化的例子.真正的html要复杂得多,也就是说,我绝对需要依赖jQuery来操作html字符串.
Aru*_*hny 43
修改jQuery对象时,它不会更改字符串文字中的值.
您可以使用
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());
Run Code Online (Sandbox Code Playgroud)
演示:小提琴
你可以找到h4然后调用replaceWith方法.
var html = $('<div><h4><a class="preview-target" href="content.html">Headline</a></h4></div>');
console.log(html.html());
html.find('h4').replaceWith('whatever')
console.log(html.html());
Run Code Online (Sandbox Code Playgroud)