簡體   English   中英

在javascript中查找jquery對象<script> tag

[英]Find a jquery object inside a javascript <script> tag

我在以下HTML頁面中有一個腳本:

<script id="scriptid" type="text/html">
    <div id="insidedivid">
        ... html code ...
    </div>
</script>

我能夠使用$("#scriptid")獲取HTMLScriptElement但我無法獲得ID為"insidedivid"的底層div對象。 這樣做的方法是什么?

這是不可能的; 瀏覽器不會將<script>標記內的HTML內容視為DOM的一部分。 當您使用$('#idhere').html()檢索<script>標記的內容時,您將獲得字符串結果。

為了回答Troy的問題,他最有可能在他的文檔的<head>中包含模板,這樣他最終可以在瀏覽器端動態呈現內容。 但是,如果是這種情況,OP應使用與text/html不同的MIME類型。 您應該使用未知的MIME類型,例如text/templates使用text/html混淆內容的用途。

你試圖進入<script>標簽並獲取div的原因是因為你在單個<script>標簽中構建了較小的子模板。 那些較小的模板應該放在它們自己的<script></script>標簽中,而不是包含在一個大的<script></script>標簽對中。

所以,而不是:

<script type="text/template" id="big_template">
    <div id="sub_template_1">
        <span>hello world 1!</span>
    </div>
    <div id="sub_template_2">
        <span>hello world 2!</span>
    </div>
</script>

做這個:

<script type="text/template" id="template_1">
    <span>hello world 1!</span>
</script>

<script type="text/template" id="template_2">
    <span>hello world 2!</span>
</script>

我認為在腳本標記內部使用div是完全有效的(或者至少是有用的),如果div對您為腳本定義的TYPE有意義。 例如,John Resig在他的微模板解決方案中使用了一個類型為“text / html”的腳本標記: http//ejohn.org/blog/javascript-micro-templating/雖然在這個例子中(並回復原文)作者)你向SCRIPT標簽添加一個ID,並參考(我不明白為什么它不適用於那種facebook類型而不是html - 但你可能想在幾個不同的瀏覽器中測試它; )。 對於您給出的示例,您可以通過執行以下操作來獲取對DIV的引用:

<script id="scriptid" type="text/html">
    <div id="insidedivid">
        ... html code ...
    </div>
</script>
    $(function(){
        alert($( $( '#scriptid' ).html() ).text() ); //alerts " ... html code ..."
    });

“技巧”是獲取腳本標記的HTML並使用jQuery轉換為DOM元素 - 但請記住,因為您將所有HTML傳遞到jQUery函數,然后您將立即選擇所有頂級元素。 在這種情況下,只有一個DIV - 所以你只是選擇它。

您的HTML無效。 HTML驗證器

如果你想擁有HTML,你就可以這樣做,使用這樣的東西:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8" />
    <title></title>
    <script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
$(document).ready(function() {
    var msg1 = $('message1');
    // Execute code here
});
    </script>
</head>
<body>
    <div id="content">Content</div>
    <div id="hidden" style="display: none">
        <div id="message1">Message 1</div>
        <div id="message2">Message 2</div>
    </div>
</body>
</html>

如果您正在制作模板系統,則可能需要使用AJAX。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM