How to style an appended div with a click event? Jquery
Here is the function that works:
/*
$("#right-sidebar").click(function() {
$(this).append("<div class='editable'>hello world</div>");
$(".editable").css("background-color","red");
});
*/
It will append a div inside of the div with id "right-sidebar" with a background color of red.
But I want there to be two different click events. One to append the inner div, and one to style it.
$("#right-sidebar").click(function() {
$(this).append("<div class='editable'>hello world</div>");
});
$(".editable").click(f开发者_C百科unction() {
$(this).css("background-color","red");
});
How would I go about doing this?
Here is the HTML:
<div id="right-sidebar">Content In Div</div>
Regards, Taylor
You can either bind the click after the appending, or use the live
binding to listen for it in advance:
$("#right-sidebar").click(function() {
$(this).append("<div class='editable'>hello world</div>");
$(".editable").click(function() {
$(this).css("background-color","red");
});
});
// Or this:
$("#right-sidebar").click(function() {
$(this).append("<div class='editable'>hello world</div>");
});
$(".editable").live("click", function() {
$(this).css("background-color","red");
});
You can also use event delegation, much more preferred:
$("#right-sidebar").click(function() {
$(this).append("<div class='editable'>hello world</div>");
})
.delegate('.editable', 'click', function() {
$(this).css("background-color","red");
});
As the editable div is added dynamically you should use the following code:
$(".editable").live("click", function () { //set as red });
All else is fine in your code
If I'm understanding correctly, the following should work:
$(function(){
$("#right-sidebar").click(function() {
$(this).append("<div class='editable'>hello world</div>");
$(".editable").click(function(event) {
event.stopPropagation();
$(this).css("background-color","red");
});
});
})
EDIT: Need to add event.stopPropogation since the .editable is contained within the #right-sidebar. Otherwise clicking on .editable will add another .editable, which I assume is not intended.
精彩评论