[英]How can I add my own <divs> to a container dynamically?
我找到了很多有關此的信息,但是還沒有找到任何可以幫助我的信息。
我的問題是我有一個帶其ID的div,它應該是一個容器( #cont_seguim
)。 我在右側有一個菜單,其中包含圓圈(由css制成並填充文本),如下所示:
<div class="circle_menu b">
<div class="text_menu n">ECO</div>
</div>
其中b和n是背景和文本的格式。 當我單擊一個圓圈時,必須將其添加到容器中(注意每個圓圈都有自己的文本),但我無法做到這一點。
我進行了數組處理,並使用alert()來測試單擊是否有效,但是行了,但是append()甚至無法打印文本,我也不知道為什么。
<script type="text/javascript">
var arrayS = new Array();
$(document).ready(function() {
$(".circulo_menu").click(function() {
var text = $(this).text();
alert("calling " + text);
$("#cont_seguim").append(text);
});
return text;
});
</script>
謝謝您的反饋!
嘗試使用html()
而不是text()
。
無法正確理解,希望以下一項對您有所幫助。
<script type="text/javascript">
$(document).ready(function() {
$(".circulo_menu").click(function() {
var myText = $(this).html();
alert("calling " + myText);
$("#cont_seguim").html(myText);
});
});
</script>
確保classname和id名稱將保持與html相同
您的代碼似乎可以正常工作( 如果您修復了html vs腳本circulo_menu
vs circle_menu
使用的其他類名 )
演示位於http://jsfiddle.net/7jbUj/
要添加整個圓圈,請使用.append(this)
附加整個元素而不是其文本
$(".circle_menu").click(function() {
$("#cont_seguim").append(this);
});
演示位於http://jsfiddle.net/7jbUj/1/
要添加圓圈的副本,以便可以添加多個副本,請首先使用.clone()
。
$(".circle_menu").click(function() {
var clone = $(this).clone(false);
$("#cont_seguim").append(clone);
});
演示位於http://jsfiddle.net/7jbUj/3/
在click
處理程序內部, this
是指clicked元素。 並且由於您將click
處理程序綁定在circle_menu
元素上, this
引用了這一點。 您可以直接將其用於附加,也可以將其克隆以首先進行復制。
試試這個: 演示
HTML:
<div class="circle_menu b">
<div class="text_menu n">ECO</div>
</div>
<div id="cont_seguim"></div>
Javascript:
$(document).ready(function() {
$(".circle_menu").click(function() {
var text = $(this).html();
console.log("calling " + text);
$("#cont_seguim").append(text);
});
});
采用
$("#container").append($("<div/>", {id:"newID",text:"sometext"}));
你可以試試
<script type="text/javascript">
var arrayS = new Array();
$(document).ready(function() {
$(".circulo_menu").click(function() {
var text = $(this).text();
alert("calling " + text);
$("#cont_seguim").append($(this).html());
});
return text;
});
</script>
通過這種方式,單擊的圓形元素將添加到div
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.