2011-04-25 24 views
2

可能有人能夠解釋我爲什麼「>」符號被編碼爲">"。 我使用MVC剃刀和我的一些CSHTML視圖使用腳本,您可以在下面找到:「>」被編碼爲「>」

<script type="text/javascript" language="javascript"> 
    $(document).ready(function() { 
     var thumbnails = $("img.thumbnail"); 
     thumbnails.each(function() { 
      $(this).load(function() { 
       if ($(this).height() > $(this).width()) { 
        $(this).css("height", "100%"); 
       } 
       else { 
        $(this).css("width", "100%"); 
       } 
      }); 
     }); 
    }); 
</script> 

Chrome瀏覽器會拋出異常:

在下一行

Uncaught SyntaxError: Unexpected token ;

if ($(this).height() &gt; $(this).width()) { 

什麼原因可以做這個編碼/變換(除了手的曲線:D)?

或以某種方式解決它。

+0

這是文檔中的預期行爲,但不在腳本標籤內。奇怪。 – 2011-04-25 19:06:48

+6

是cshtml的XML嗎?如果是這樣,那麼你需要將所有的JS包裝在CDATA註釋中。 – 2011-04-25 19:07:30

+0

這樣做的原因是您的模板引擎認爲輸出應該在瀏覽器中可讀,所以它將'<', '>'和'&'字符更改爲它們的HTML實體等價物。如何解決這個問題取決於你正在做什麼將這些東西發送給用戶。 – geoffspear 2011-04-25 19:07:51

回答

4

嘗試

<script type="text/javascript" language="javascript"> 
    <![CDATA[ 
     $(document).ready(function() { 
      var thumbnails = $("img.thumbnail"); 
      thumbnails.each(function() { 
       $(this).load(function() { 
        if ($(this).height() > $(this).width()) { 
         $(this).css("height", "100%"); 
        } 
        else { 
         $(this).css("width", "100%"); 
        } 
       }); 
      }); 
     }); 
    ]]> 
</script> 

要不然就把你的JavaScript在外部JavaScript文件。

+0

謝謝!有很好的文章介紹瞭如何解決這個問題:http://javascript.about.com/library/blxhtml.htm - 無論如何,我需要了解這種行爲的原因。再次感謝你們! – 2011-04-25 19:57:30

相關問題