2014-01-27 46 views
0

我想創建一個div來處理一些圖像,但我不想將它附加到正文部分。用jquery動態創建div

我想使用一個js文件來保存我的代碼,這樣我就可以將它加載到我的wordpress側邊欄中。 也是我的代碼檢查是否jQuery是加載,如果它是不是會加載並運行代碼

我的代碼是:

function myJQueryCode() { 
    //Do stuff with jQuery 
$(document).ready(function(){ 

$("body").append('<div id="theContentsm" class="theContentsm" style="width:100%; padding-bottom:5px;"></div>'); 
//I don't want append it to body just to create it so it can holds the div bellow! 

$('<div class="items" id="link_'+tsource1id+'" style="width:110px; height:100px; float:left; margin:20px; background-color:#333;"></div>').html('<a href="'+tsource1+'"><img src="'+tsource1img+'" width="600" height="350" alt="xxx" style="width:104px; height:94px; float:left; margin-left:3px; margin-top:3px;" width="104" height="94"></a>').appendTo('#theContentsm'); 

$('<div class="brief_'+tsource1id+'" style="width:110px; height:100px; float:left; margin-top:3px; padding-bottom:3px; text-align:center;"></div>').html(tsource1caption).appendTo('#link_'+tsource1id); 

}); 
} 

//Checking if jquery is loaded.. 
if(typeof jQuery=='undefined') { 
    var headTag = document.getElementsByTagName("head")[0]; 
    var jqTag = document.createElement('script'); 
    jqTag.type = 'text/javascript'; 
    jqTag.src = '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'; 
    jqTag.onload = myJQueryCode; 
    headTag.appendChild(jqTag); 
} else { 
    myJQueryCode(); 
} 

,我會加載它是這樣的:

<script type="text/javascript" src="http://www.mydomain.com/scripts/myjavascript.js"></script> 
+0

什麼是症狀/控制檯消息,如果有的話? – mplungjan

+0

你能夠創建div並將其附加到正文嗎? –

+0

@mplungjan當我使用代碼加載包含代碼的js文件時,出現..我必須使用jQuery的noConflict? –

回答

1

也許你的意思是

function myJQueryCode() { 
    $(function(){ 
    $('<div id="theContentsm" class="theContentsm" style="width:100%; padding-bottom:5px;"></div>') 
    .append('<div class="items" id="link_'+tsource1id+'" style="width:110px; height:100px; float:left; margin:20px; background-color:#333;"></div>').html('<a href="'+tsource1+'"><img src="'+tsource1img+'" width="600" height="350" alt="xxx" style="width:104px; height:94px; float:left; margin-left:3px; margin-top:3px;" width="104" height="94"></a>') 

    $('<div class="brief_'+tsource1id+'" style="width:110px; height:100px; float:left; margin-top:3px; padding-bottom:3px; text-align:center;"></div>').html(tsource1caption).appendTo('#link_'+tsource1id); 

    }); 
} 

,而不是所有的瀏覽器都支持的onload腳本

'onload' handler for 'script' tag in internet explorer

+0

我在我的控制檯中得到了這個錯誤未捕獲的ReferenceError:$未定義 –

+0

我的代碼在我將它包含在本地html文件中時工作...是任何問題,我在其他域/服務器中的.js文件? –

0

我解決了它.. 我刪除行

$("body").append('<div id="theContentsm" class="theContentsm" style="width:100%; padding-bottom:5px;"></div>'); 

而且我手動創建一個div

<div id="theContentsm" class="theContentsm" style="width:100%; padding-bottom:5px;"></div> 

和插入我的javascript波紋管吧!