2017-08-23 71 views
0

請是可能加載腳本標籤內的一些HTML元素表現出來,並使用類名怎樣把HTML腳本標籤中,並使用jquery

<script id="scripttags"> 
    <div class="item-1">Hello</div> 
    <div class="item-2">Hello2</div> 
    <div class="item-3">Hello</div> 
</script> 

訪問它訪問的任何一個:

<script> 
    var loadit = $('script#scripttags item-2').clone(); 
    alert(loadit); 
<script> 

請反正我可以這樣做嗎?

+2

呃什麼......爲什麼?腳本是爲js - 不是html – ThisGuyHasTwoThumbs

+0

你可以; t把html元素放在腳本標記中,而不是你可以動態地追加html如果你想要 –

+0

@ThisGuyHasTwoThumbs是的我知道爲什麼我要加載我的html然後使用id或class來訪問它名字 –

回答

0

我建議使用車把,但它也可以用純JS/jQuery的完成:

<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title>Title</title> 
 

 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
</head> 
 
<body> 
 
    <script id="scripttags" type="text/html"> 
 
     <div class="item-1">Hello</div> 
 
     <div class="item-2">Hello2</div> 
 
     <div class="item-3">Hello</div> 
 
    </script> 
 
    <script type="text/javascript"> 
 
     var el = $('<div></div>'); 
 
     el.html($('#scripttags').text()); 
 
     var loadit = el.find('.item-2').html(); 
 
     alert(loadit); 
 
</script> 
 
</body> 
 
</html>

我把你的腳本標籤的內容中動態創建的股利,並在此它的行爲像正常的DOM

0

使用handlebars.js創建模板。編譯後將它綁定到json數據。然後,你可以顯示html。您還可以使用其他模板庫,例如mustache.js,underscore.js模板等

下面的代碼是從 http://handlebarsjs.com

<script id="entry-template" type="text/x-handlebars-template"> 
<div class="entry"> 
<h1>{{title}}</h1> 
<div class="body"> 
{{body}} 
</div> 
</div> 
</script> 

這個定義的模板。然後,您可以使用它,如下所示。

<script type="text/javascript"> 
    var source = $("#entry-template").html(); 
    var template = Handlebars.compile(source); 
    var context = {title: "My New Post", body: "This is my first post!"}; 
    var html = template(context); 
    </script> 
0

你可以這樣做:

$("body").html(
    '<div class="item-1"> 
    Hello 
    </div> 

    <div class="item-2"> 
    Hello2 
    </div> 

    <div class="item-3"> 
    Hello3 
    </div>' 
); 

這裏,body所需alement可以添加/轉讓/追加。

相關問題