2013-02-06 61 views
4

我想創建使用jquery的元素。當我點擊一個鏈接時,我想創建一個元素「p」,給它一些文本,然後把它放在我的一個div中。此外,我想檢查哪個鏈接被點擊,所以我可以把創建的「p」在正確的div。任何解決方案,我在哪裏做錯了?使用jquery動態創建元素

使用Javascript/jQuery的

$(document).ready(function() { 

function createElement() { 
    var a = $("#menu").find('a').each(function(){ 
    if(a == "l1"){ 
    var text = $(document.createElement('p'); 
    $('p').text("Hej"); 
    $("#contentl1").append("text"); 
    } 
    }); 
} 

$("#menu").find('a').each(function() { 
    $(this).click(function() { 
     createElement(); 
    }); 
}); 

createElement(); 

}); 

HTML

 <html> 

<head> 
<title>Inl1-1</title> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<link rel="stylesheet" type="text/css" href="style-1.css"> 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> 
<script type="text/javascript" src="Uppg1.js"></script> 
</head> 

<body> 

<ul class="meny" id="menu"> 
<li><a href="#" id="l1">Utvärdering/Feedback</a></li> 
<li><a href="#" id="l2">Kontakt</a></li> 
<li><a href="#" id="l3">Öppettider</a></li> 
<li><a href="#" id="l4">Om Asperöd</a></li> 
</ul> 

<div id="contentl1"> 

</div> 

<div id="contentl2"> 

</div> 

<div id="contentl3"> 

</div> 

<div id="contentl4"> 

</div> 

</body> 

</html> 
+0

首先,你..'變種文字= $(使用document.createElement(「P」);'錯過 – Dimser

+0

您使用的是可變的右括號中的條件,其返回值,應該說在函數內部變量?var a = $(「#menu」)。find('a')。each(function(){if(a ==「l1」){ – Simon

回答

13

這裏是用文字添加新<p>元素「HEJ」#contentl1的最佳方式使用jQuery:對於開始點擊功能可以這樣做具有代替

$("<p />", { text: "Hej" }).appendTo("#contentl1"); 
2
function createElement() { 
    var a = $("#menu").find('a').each(function(){ 
    if(a == "l1"){ 
    var p = $("<p>"); 
    p.text("Hej"); 
    $("#contentl1").append(p); 
    } 
    }); 
} 
1

我知道這並不realate來回答你的問題,但它是很難離開這個作爲一個評論:

var a = $("#menu").find('a').each(function(){ <-- this "a" will only be created after the each completes 
    if(a == "l1"){ <-- this "a" that you are verifying is a global variable 
    var text = $(document.createElement('p'); 
    $('p').text("Hej"); 
    $("#contentl1").append("text"); 
    } 
    }); 

您可以嘗試以解決您的問題:

function createElement() { 
    if($(this).attr("id") == "l1"){ 
    $("#contentl1").append('<p>hej</p>'); 
    } 
} 

$("#menu a").each(function() { 
    $(this).click(function() { 
     createElement.apply(this); 
    }); 
}); 
1

使用.find():

$('#menu a').click(function() { } 

的。每()循環可以像做

$('#menu a').each(function() { 
    var aId = $(this).attr('id'); 
    var contentId = content + aId; 
    $(contentId).append('<p>Hej</p>'); 
}) 
0

類似於this fiddle

$('#menu').on('click', 'a', function(e) { 
    e.preventDefault(); 
    $('<p>').text($(this).text()).appendTo('#content'+this.id); 
}); 
0

試試這個腳本,它會把文本放在正確的div

$(document).ready(function() { 

$("#menu").find('a').each(function() { 
    $(this).on('click',function() { 
     $("#content"+$(this).attr("id")).append("<p>link "+$(this).attr("id")+" is clicked</p>"); 
    }); 
}); 


});