Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jquery替换/操作html字符串中的元素_Javascript_Jquery_String - Fatal编程技术网

Javascript 使用jquery替换/操作html字符串中的元素

Javascript 使用jquery替换/操作html字符串中的元素,javascript,jquery,string,Javascript,Jquery,String,我有一个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 "w

我有一个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);
var html='';
log(html);
var elem=$('h4',$(html));
//将“Headline”替换为“whatever”=>不起作用
元素替换为(“任何”);
log(html);
我有一个JSFIDLE用于测试

上面的代码只是一个简化的示例。真正的html要复杂得多,也就是说,我肯定需要依赖jQuery来处理html字符串;
var html = '<div><h4><a class="preview-target" href="content.html">Headline</a></h4></div>';
var replaced=html.replace("Headline","whatever");
console.log(replaced);
var replaced=html.replace(“标题”、“任何内容”); 控制台日志(已替换);
当您修改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());
var html='';
log(html);
var$html=$('',{html:html});
//将“Headline”替换为“whatever”=>不起作用
$html.find('a').html(“任意”);
log($html.html());

演示:

您可以找到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());
var html=$('');
log(html.html());
html.find('h4').replaceWith('whatever'))
log(html.html());

可以,但是为什么我上面的代码不起作用呢?我上面的代码只是一个简化的例子,真正的代码是更难的html,我无法使用simple
replace
方法来处理。所以我需要jQuery@A.Wolff好的,但这只适用于我的最小工作示例代码,而不适用于我更复杂的代码。在这里,我需要依赖jQuery。我更新了关于“当您修改jQuery对象时,它不会更改字符串文本中的值”的问题。这是为什么?对我来说好像是个虫子@ArunPJohny我不理解var$html=$('',{html:html});这段代码到底是做什么的?看起来你创建了一个对象?这是关于什么的?这是添加到原始HTML还是选择现有字符串中的div?@AdamYoungers
$(“”,{HTML:HTML})
-创建一个dom div元素,并将
html
的值设置为其
innerHTML
…它不会更改字符串文本中的值-重要键在这里。“$($('select').html())”将执行此操作,并执行您想要的任何操作,如$($('select').html()).find('h4').remove()