2011-04-25 69 views
0

我有这个功能的一个问题:如何在此函数中使用JQuery设计动态创建的div?

$("#contentdiv").click(function() { 
    $(this).append("<div class='editable'>For some reason this div cannot be colored</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").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 
     } 
    } 
} 

它允许你改变一个div的背景颜色与类“编辑”

首先,你与ID为“一个div点击#background_color_button“,它将检索其上方文本输入的值,然后单击要将样式应用于的div(带有class =”editable“)。

我的问题是在这里:

$("#contentdiv").click(function() { 
    $(this).append("<div class='editable'>For some reason this div cannot be colored</div>"); 
}) 

这个函数创建带class = “编辑” 与ID = “contentdiv” 的div内一个div。

但是,虽然它有class =“editable”,但点击ID =“background_color_button”的div,然后在动态创建的div上不会导致样式改变,就像不使用jQuery动态加载的div一样。

我知道,你可以使用:

.delegate('.editable', 'click', function() { 
    $(this).css("background-color","red"); 
}); 

$(".editable").live("click", function() { 
    $(this).css("background-color","red"); 
}); 

要做到这一点,但是当我试图把线:

.delegate('.editable', 'click', function() { 

$(".editable").live("click", function() { 

在地方:

$("div.editable").click(function(e) { 

的功能不再起作用。

非常感谢你提前,

泰勒

这里是一个的jsfiddle文档与项目:

http://jsfiddle.net/TSM_mac/gJLSd/1/

+0

你想要做这样的事吗? http://jsfiddle.net/MTsk3/3/ – Shaz 2011-04-25 22:43:32

回答

1

这是因为你的#contentdiv专区内及附加这些事件不会冒泡。

因此,如果您更改这个HTML:

<div id="contentdiv">Click here to make a div</div>

这样:

<div id="contentdiv"><span id='clicker'>Click here to make a div</span></div>

,然后JS来自:

$("#contentdiv").click(function() { 
    $(this).append("<div class='editable'>For some reason this div cannot be colored</div>"); 
}) 

... 
... 

$("div.editable").click(function(e) { 
    //blah blah blah 
}); 

这样:

$("#clicker").click(function() { 
    $(this).parent().append("<div class='editable'>For some reason this div cannot be colored</div>"); 
}) 

... 
... 

$("div.editable").live("click",function(e) { 
    //blah blah blah 
});

一切正常!

+0

只记得添加div:

For some reason this div cannot be colored
我看到这些事件现在没有冒泡。我做了修复,而且效果很好! – TaylorMac 2011-04-26 01:09:56

+0

很高兴能请您将此问题标记为已回答。 – locrizak 2011-04-26 13:55:38