【问题标题】:Dynamically change the background-color of a dynamically created div using Jquery使用 Jquery 动态更改动态创建的 div 的背景颜色
【发布时间】:2011-08-12 17:09:03
【问题描述】:

我有两组函数,一组改变 div 的背景颜色(一个动态创建的 div 或一个已经存在的)第二组在具有 class="divplace" 的 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(使用 class="divplace"),在不添加新 Div 的情况下,您无法更改创建的 Div 的颜色。我希望能够在 Div 中创建无限数量的 Div,并且总是在不添加新 Div 的情况下更改它们的颜色。

非常感谢!

泰勒

【问题讨论】:

  • 而不是(基本上)使用$currentInput$currentDiv 作为全局变量,您应该真的将它们作为参数传递,如下所示:function GetCssProperties($input) { var value = $input.val(); ... }

标签: jquery jquery-selectors javascript


【解决方案1】:

查看示例后,我认为您想要做的只是执行您选择的最后一个操作(颜色更改或添加 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 和 if 是没有意义的。这是等价的:

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

【讨论】:

  • 是的!这就是我试图做的,但无法弄清楚。也感谢您在代码中找到多余的地方。我很感激
  • @taylormac $currentDiv 在等效代码中根本不需要设置为 null。下一行将其设置为不同的值,因此不需要它。
猜你喜欢
  • 2014-08-06
  • 2014-04-05
  • 1970-01-01
  • 2012-04-30
  • 1970-01-01
  • 2014-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多