繁体   English   中英

使用Jquery动态更改动态创建的div的背景颜色

[英]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),而不是全部执行。 如果是这样,它将这样做:

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

基本上,单击一个动作后,将清除另一个动作。 这样,每次单击都会更改颜色或添加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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM