0

Suppose I have a variable which store html markup:

var $content=$("<div id='test'></div>")

then I want give it a click event,and append it to body element

$content.click(function(){
    console.log('click!');
});

$content.appendTo($('body'))

however it doesn't work ,how can I make it possible?

hh54188
  • 14,887
  • 32
  • 113
  • 184

1 Answers1

0

The click handler gets set up just fine. The problem is that with a completely empty div, it has a height of 0 (unless you've done styling somewhere that you haven't shown), and so you can't find it to click on it. Zero-height example | source.

The solution is to put content in the div, or to give it styling to give it height:

Content example | source:

var $content=$("<div id='test'>I'm the div!</div>");
$content.click(function(){
    console.log('click!');
});
$content.appendTo($('body'));

Styling example | source:

JavaScript:

var $content=$("<div id='test'></div>");
$content.click(function(){
    console.log('click!');
});
$content.appendTo($('body'));

CSS:

#test {
    height: 20px;
    border: 1px solid black;
}

Side note:

Suppose I have a variable which store html markup:

var $content=$("<div id='test'></div>");

Note that you're not storing HTML markup. By calling jQuery with HTML markup, you're telling jQuery to create the relevant DOM elements and wrap them in a jQuery instance.

To store markup in a variable, you'd just store the string containing the markup:

var content="<div id='test'></div>";

Markup is text; elements are objects.


Update: Re your comment below:

I write this code in jquery plugin js file...does it have some matter?

It matters if your code is running before there's a body element to append to; your last line will fail without a body element (for instance, if you code is running immediately on load, and it's loaded from the head element). If the body element exists as of when you run your code, it should be fine.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • no,I think if I set a height to it,it also doesn't work.In my real case,it's a option tag – hh54188 Apr 05 '12 at 08:40
  • @hh54188: If you set a height, it does work. See the examples I added. – T.J. Crowder Apr 05 '12 at 08:41
  • @T:alright...I write this code in jquery plugin js file...does it have some matter? – hh54188 Apr 05 '12 at 08:43
  • @hh54188: Not unless your code is running before the `body` element exists. See update. If you quote the relevant code, do a proper failing test case, it's a lot easier to help you. – T.J. Crowder Apr 05 '12 at 08:48