【发布时间】: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