javascript - How to dynamically add a tag within a div and access it on click? - Stack Overflow

My div structure should be this:<div id="dashboard"><img id="pic1" src=&qu

My div structure should be this:

<div id="dashboard">
    <img id="pic1" src="...png" />
    <h6>....</h6>       
</div>

To create the div I use this:

$('<div>', {
    'id': 'dashboard'
}).appendTo('body');

I need to append a h6 tag with text into the above div. How can this be done? Also how can I access the text within the h6 tag when the div is clicked?

$('#dashboard div').hover(function() {
    alert($(this).children().eq(2)  ??  );
};

My div structure should be this:

<div id="dashboard">
    <img id="pic1" src="...png" />
    <h6>....</h6>       
</div>

To create the div I use this:

$('<div>', {
    'id': 'dashboard'
}).appendTo('body');

I need to append a h6 tag with text into the above div. How can this be done? Also how can I access the text within the h6 tag when the div is clicked?

$('#dashboard div').hover(function() {
    alert($(this).children().eq(2)  ??  );
};
Share Improve this question edited Dec 19, 2016 at 8:30 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Feb 24, 2012 at 10:51 user1184100user1184100 6,90430 gold badges84 silver badges122 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

To add the h6 element, try this:

var $div = $('<div>', {
    'id':'dashboard'
}).appendTo('body');

$("<h6></h6>").text("Foo").appendTo($div);

To access the text of the h6 on click of the div, try this:

$("body").delegate("#dashboard", "click", function() { 
    var text = $("h6", this).text();
    alert(text);
});

That assumes you are using jQuery 1.6 or lower. If you are using jQuery 1.7+, you can use on():

$("body").on("click", "#dashboard", function() { 
    var text = $("h6", this).text();
    alert(text);
});

Example fiddle

Also, I have used $("body") here as an example - you should use a selector which is the closest to the element you are attaching the event to (in this case #dashboard) which is not dynamically created.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745340791a4623316.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信