用jQuery每个函数更新外部变量

时间:2018-01-31 21:06:35

标签: javascript jquery

我正在测试一个简单的脚本,我将html字符串存储到变量中,并希望替换它的一部分。我的实际代码是一个很大的html字符串,在这种情况下我不能使用replace(),因为我在each()中有wrap()和nextSibling()函数。

<script>
var htmlvar = "<html><head></head><body><p><i>test</i></p></body></html>";

htmlvar = $(htmlvar).find('i').each(function() {

          $(this).html('changed');

});

console.log('value: '+htmlvar[0].outerHTML);
</script>

运行以上输出后:

<i>changed</i>

我想在每个()函数执行某些标记的逻辑后仍然拥有完整的html标记。有没有办法实现这个目标?

编辑:

同样适用于文档对象

<body>
<p><i>test</i>

<script>

    $(document).find('i').each(function() {

              $(this).wrap('<h1></h1>');

    });

    console.log('value: '+$(document).find('html').html());
    </script>

</body>

输出是当前文档的完整html。

2 个答案:

答案 0 :(得分:0)

如果将字符串转换为包装在JQuery对象内的实际DOM节点,则不需要.find。您只需在节点中搜索i元素(使用JQuery选择器的context参数)并更改其文本。

var $htmlvar = $("<html><head></head><body><p><i>test</i></p></body></html>");
console.log($htmlvar[0].outerHTML);
$("i", $htmlvar).text('changed');
console.log($htmlvar[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:-1)

使用append()代替html()。顾名思义,它会附加一个给定的字符串,而不是替换整个元素。

$(this).append('changed');