[英]Dynamically change the background-color of a dynamically created div using Jquery
我有兩組函數, 一組可更改div的背景顏色 (動態創建的div或已經存在的一個) ,第二組可在具有class =“ divplace”的div內添加新的div 。
單擊事件的工作方式如下:1)單擊ID為“ background_color_button”的“按鈕”,然后在div上將背景色更改為該顏色。 或 2)點擊ID為“ clicker”的“按鈕”,在div中添加一個div。
這是第一個:
var $currentInput = null;
$("#background_color_button").live("click", function() {
$currentInput = null;
if ($currentInput == null) {
$currentInput = $(this).prev();
$("label").html($currentInput.attr("id"));
}
});
var editid;
$("div.editable").live("click",function(e) {
e.stopPropagation();
if ($currentInput == null)
return;
var css = GetCssProperties();
$(this).css(css);
$("label").html("");
});
function GetCssProperties() {
if ($currentInput == null) return null;
var value = $currentInput.val();
if ($currentInput.attr("id") == "background-color") {
return {
"background-color": value
}
}
}
這是第二個:
var $currentDiv = null;
$("#clicker").live("click", function() {
$currentDiv = null;
if ($currentDiv == null) {
$currentDiv = $(this).prev();
$("label").html($currentDiv.attr("id"));
}
});
var editid;
$(".divplace").live("click",function(e) {
e.stopPropagation();
if ($currentDiv == null)
return;
var newdiv = "<div class='editable divplace'>The Div created inside of this div needs to be able to change the BG color without adding a new div</div>";
$(this).append(newdiv);
$("label").html("");
});
這是JSFiddle文檔:
http://jsfiddle.net/TSM_mac/QYAB9/
我的問題是,一旦在Div內的Div中創建Div(帶有class =“ divplace”),就不能在不添加新Div的情況下更改已創建Div的顏色。 我希望能夠在Divs中創建無限數量的Divs,並始終更改其顏色而無需添加新Divs。
非常感謝!
泰勒
看完示例之后,我認為您只想執行選擇的最后一項操作(更改顏色或添加div),而不是全部執行。 如果是這樣,它將這樣做:
基本上,單擊一個動作后,將清除另一個動作。 這樣,每次單擊都會更改顏色或添加div,但不會兩者都更改。
此外,還有許多方法可以改進您的代碼。 尤其:
$currentDiv = null;
if ($currentDiv == null) {
$currentDiv = $(this).prev();
$("label").html($currentDiv.attr("id"));
}
您正在設置$ currentDiv = null,然后檢查它是否為null。 由於將其設置為null,因此它將始終為null。 然后將其設置為其他值,基本上= null和if沒有意義。 這是等效的:
$currentDiv = $(this).prev();
$("label").html($currentDiv.attr("id"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.