2010-01-31 36 views
12

爲什麼此代碼的工作:爲什麼我不能用JQuery .html添加<br />?

$('div.error_container').html('<div class="error">No more foo allowed</div>'); 

但這種代碼導致錯誤:

$('div.error_container').html('<div class="error">No more foo allowed<br /></div>'); 

我試圖把<br />前後</div>標籤,同樣的錯誤了。我試過將它從<br />更改爲<br>。 Chrome瀏覽器總是說,在檢查的情況如下:

Uncaught SyntaxError: Unexpected token ILLEGAL 

回答

14

儘量分解成一個鏈條:

var $div = $('<div class="error"></div>').html('No more foo allowed') 
             .append('<br />'); 
$('div.error_container').html($div); 
+0

這樣做。我想知道爲什麼,但現在我很高興它可以工作。 –

+3

奇怪的是,我今天遇到了類似的問題(帶有br標籤),並將其分解爲嬰兒步驟解決了它。我也想知道爲什麼jQuery不喜歡創建/附加包含換行符的元素。 – karim79

+0

我感覺其他人對於doctype角度是正確的。 – karim79

3

這完美的作品對我來說:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html> 
<head> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script> 
<script type="text/javascript"> 
$(function() { 
    $('div.error_container').html('<div class="error">No more foo allowed<br /></div>'); 
}); 
</script> 
</head> 
<body> 
<div class="error_container"> 
</div> 
</body> 
</html> 
在Chrome和Firefox

。你使用的是什麼版本的jQuery?

附註<br />是XML(包括XHTML)而非HTML。 HTML是<br>

+0

再次閱讀我的問題,cletus。尤其是我說「我treid [原文如此]將它從
更改爲
」的部分。「 –

+1

如果上述不起作用(您明確指出「嘗試」;)),那麼請嘗試*'

'。 – BalusC

+3

我也試過這個。有趣的是,我使用
,


,在所有情況下瀏覽器報告它得到了
並且給我錯誤似乎並不重要。 –

3

我嘗試以下SSCCE和它完美的作品在IE,FF,Safari瀏覽器,歌劇和鉻(所有最新版本)。

因此,您的問題可能與您聲明的文檔類型或使用舊版本的Chrome相關。

<!doctype html> 
<html lang="en"> 
    <head> 
     <title>SO question 2173556</title> 
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
     <script> 
      $(document).ready(function() { 
       $('#foo').html('<div>foo<br>foo</div>'); 
       $('#bar').html('<div>bar<br/>bar</div>'); // Yes, that's illegal in HTML strict. Just to test :) 
      }); 
     </script> 
     <style> 

     </style> 
    </head> 
    <body> 
     <div id="foo"></div> 
     <div id="bar"></div> 
    </body> 
</html> 
相關問題