【问题标题】:jQuery using string as jQuery object for DOM manipulationjQuery 使用字符串作为 jQuery 对象进行 DOM 操作
【发布时间】:2012-08-26 21:30:40
【问题描述】:
myVariable 是一个包含 HTML 的字符串。
为了操纵它,我正在做以下事情:
$(myVariable).find('div.grid-12-12').each(function() {
$(this).attr('class','grid-2-12');
alert($(this).attr('class'));
});
我在警报中看到的始终是grid-12-12。
是否找到了正确的div,但似乎更改未保存在myVariable中。
你能帮帮我吗?
【问题讨论】:
标签:
jquery
string
object
dom
【解决方案1】:
当您调用$(myVariable) 时,它会创建一个包含myVariable 内容的DOM 元素,然后您的attr 调用会修改该元素。 myVariable 的原始内容不会受到任何影响,因为它只是文本。
如果您想取回操作将产生的文本表示,您可以将其附加到一个空元素,然后检索其 html 内容:
var newElement = $(myVariable)... // your code
myVariable = $("<p/>").append(newElement).html();
或简单地说(如果支持):
myVariable = newElement[0].outerHTML;
【解决方案2】:
尝试清理浏览器缓存。在这里工作。看:
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Index JQuery Mobile</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#busca').find('div.grid-12-12').each(function() {
$(this).attr('class', 'grid-2-12');
alert($(this).attr('class'));
});
});
</script>
</head>
<body>
<div id="busca">
<div class="grid-12-12"></div>
<div class="grid-12-12"></div>
<div class="grid-12-12"></div>
<div class="grid-12-12"></div>
<div class="grid-12-12"></div>
</div>
</body>
</html>