How to style a dynamically created div using JQuery in this function?
I have a problem with this function:
$("#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
}
}
}
It allows you to change the background color of a div with the class "Editable"
First you click on a div with the ID "#background_color_button" and it will retrieve the value of the text input above it, and then you click on the div (With class="editable") that you want the style to be applied to.
My problem is here:
$("#contentdiv").click(function() {
$(this).append("<div class='editable'>For some reason this div cannot be colored</div>");
})
This function creates a div with class="editable" inside of the div with ID="contentdiv".
However, although it has the class="editable", clicking on the div with ID="background_color_button" and then on the dynamically created div will not cause the style to change like the divs which are NOT dynamically loaded using jQuery.
I know that you can use:
开发者_Python百科.delegate('.editable', 'click', function() {
$(this).css("background-color","red");
});
or
$(".editable").live("click", function() {
$(this).css("background-color","red");
});
To accomplish this, but when I try to put the line:
.delegate('.editable', 'click', function() {
or
$(".editable").live("click", function() {
In place of:
$("div.editable").click(function(e) {
The function no longer works.
Thank you very much in advance,
Taylor
Here is a JSfiddle doc with the project:
http://jsfiddle.net/TSM_mac/gJLSd/1/
It is because you are appending within the #contentdiv div and the events are not bubbling down.
So if you change the html from this:
<div id="contentdiv">Click here to make a div</div>
to this:
<div id="contentdiv"><span id='clicker'>Click here to make a div</span></div>
and then the js from:
$("#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
});
to this:
$("#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
});
Everything works!
精彩评论