[英]jQuery using string as jQuery object for DOM manipulation
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
。
你能幫我么?
當您調用$(myVariable)
它將創建一個包含myVariable
內容的DOM元素,然后您的attr
調用將修改該元素。 myVariable
的原始內容不會受到任何影響,因為它只是文本。
如果要獲取操作將產生的文本表示形式,可以將其附加到一個空元素,然后檢索其html內容:
var newElement = $(myVariable)... // your code
myVariable = $("<p/>").append(newElement).html();
或簡單地(如果支持):
myVariable = newElement[0].outerHTML;
嘗試清理瀏覽器緩存。 在這里工作。 看:
<!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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.