2011-04-26 53 views
0

我有兩套功能,其中一個改變div的背景顏色(一個動態創建的div或一個已經存在的)和第二個在div =中添加了具有class =「divplace」的新div。動態改變動態創建的div使用jquery的背景顏色

點擊事件的工作是這樣的: 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(With cla ss =「divplace」),你不能改變創建的Div的顏色而不添加新的Div。我希望能夠在Div內創建無限量的Div,並且始終在不添加新Div的情況下更改其顏色。

非常感謝!

泰勒

+1

而不是使用'$ currentInput'和'$ currentDiv'爲全局變量(基本),你應該** **真的通過他們作爲參數,就像這樣:'功能GetCssProperties($輸入) {var value = $ input.val(); ...}' – 2011-04-26 02:15:11

回答

0

看例子之後,我覺得你想要做的僅僅是執行你所選擇的最後一個動作(無論是顏色的改變或添加的div),而不是兩個。如果是這樣,這將做到這一點:

http://jsfiddle.net/QYAB9/3/

基本上,當點擊一個動作另一個被清除。這種方式每次點擊或者改變顏色或者添加一個div,但不是兩者。

此外,還有很多方法可以改進您的代碼。特別是:

$currentDiv = null; 
if ($currentDiv == null) { 
    $currentDiv = $(this).prev(); 
    $("label").html($currentDiv.attr("id")); 
} 

您正在設置$ currentDiv = null,然後檢查它是否爲空。它將始終爲空,因爲您將其設置爲空。然後你把它設置成別的東西,基本上= null和if是毫無意義的。這是equivilent:

$currentDiv = $(this).prev(); 
$("label").html($currentDiv.attr("id")); 
+0

是的!這正是我想要做的並且無法弄清楚的。感謝您在代碼中找到多餘的地方。我非常感激 – TaylorMac 2011-04-26 03:23:29

+0

這個作品很棒。再次感謝你! – TaylorMac 2011-04-26 04:29:12

+0

@taylormac $ currentDiv不需要在等效代碼中設置爲null。下一行將其設置爲不同的值,因此不需要。 – 2011-04-26 13:02:28