最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论