Javascript creating <div> on the fly
I have aa link that looks similar to this
<a href="/home/category/blog/1" id="blog">Blog</a>
As you can the link has an ID of 'blog' what I want to do is to create an div on the fly with the ID from the link that was clicked so if the 'blog' is clicked, then the markup would be
<div id="blog">
<!--some content here-->
</div>
Like wise if for instance the news link is clicked then I would like,
<div id="news">
<!--some content here-->
</div>
to be created in the markup if this possible? and how Im pretty new to jQuery.
Try this:
$("a").click(function(){
$("#wrapper").append("<div id=" + this.id + "></div>");
});
Not tested, should work ;) where: #wrapper
is parent element, work on all a
as you see.
You will need to give the div a different ID. Perhaps you could give it a class instead:
$("#blog").click(function() {
$(this).after("<div class='blog'>...</div>");
return false;
});
That's just one of many ways to create a div. You probably also want to avoid duplicates however in which case, use something like this:
$("#blog").click(function() {
var content = $("#blog_content");
if (content.length == 0) {
content = $("<div></div>").attr("id", "blog_content");
$(this).after(content);
}
content.html("...");
return false;
});
As for how to handle multiple such links I would do something like this:
<a href="#" id="blog" class="content">Blog</a>
<a href="#" id="news" class="content">News</a>
<a href="#" id="weather" class="content">Weather</a>
<div id="content"></div>
with:
$("a.content").click(function() {
$("#content").load('/content/' + this.id, function() {
$(this).fadeIn();
});
return false;
});
The point is this one event handler handles all the links. It's done cleanly with classes for the selector and IDs to identify them and it avoids too much DOOM manipulation. If you want each of these things in a separate <div>
I would statically create each of them rather than creating them dynamically. Hide them if you don't need to see them.
尝试这个 :
<a id="blog">Blog</a>
<a id="news">news</a>
<a id="test1">test1</a>
<a id="test2">test2</a>
$('a').click(function()
{
$('<div/>',{
id : this.id,
text : "you have clicked on : " + this.id
}).appendTo("#" + this.id);
});
链接地址: http://www.djcxy.com/p/83356.html
上一篇: 使用javascript / jquery动态创建div
下一篇: 动态创建<div>的JavaScript