2012-08-26 88 views
0

myVariable是一個包含HTML的字符串。jQuery將字符串用作DOM操作的jQuery對象

爲了操縱它,我做以下操作:

$(myVariable).find('div.grid-12-12').each(function() { 
      $(this).attr('class','grid-2-12'); 
         alert($(this).attr('class')); 
     }); 

我在警報看到總是grid-12-12。 它是否找到了正確的div,但似乎該更改未保存在myVariable

你能幫我嗎?

+1

http://blog.slaks.net/2011/01/modifying-html-strings-using-jquery.html – SLaks

回答

1

當您撥打$(myVariable)時,它會創建一個內容爲myVariable的DOM元素,然後您的attr調用將修改該元素。 myVariable的原始內容不受任何影響,因爲它只是文字。

如果你想找回什麼樣的操作會產生的文字表述,您可以將其添加到一個空的元素,然後檢索它的HTML內容:

var newElement = $(myVariable)... // your code 
myVariable = $("<p/>").append(newElement).html(); 

或者乾脆(如果支持的話):

myVariable = newElement[0].outerHTML; 
0

嘗試使用乾淨的瀏覽器緩存。在這裏工作。 Look:

<!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>