Dynamically adding a div element in jquery
I use the following function to show a status message after a form submit from my asp.net page.. The function gets called but it(alertmsg div) doesn't seem to show up why?
function topBar(message) {
var $alertdiv = $('<div id = "alertmsg"/>');
$alertdiv.text(message);
alert($alertdiv);
alert($alertdiv.开发者_运维百科text(message));
$alertdiv.click(function() {
$(this).slideUp(200);
});
$(document.body).append($alertdiv);
setTimeout(function() { $alertdiv.slideUp(200) }, 5000);
}
What happens is both the alert statements show [Object object]
... I think both need to show different outputs... Any suggestion..
css:
#alertmsg
{
font-family:Arial,Helvetica,sans-serif;
font-size:135%;
font-weight:bold;
overflow: hidden;
width: 100%;
text-align: center;
position: absolute;
top: 0;
left: 0;
background-color: #404a58;
height: 0;
color: #FFFFFF;
font: 20px/40px arial, sans-serif;
opacity: .9;
}
You're alerting the jQuery object. Try changing your alert to:
alert($alertdiv.get(0).innerText);
Other than that, your div may not be showing because you're adding the click event before you add the div element to the page.
Try changing:
$alertdiv.click(function() {
$(this).slideUp(200);
});
To:
$alertdiv.bind('click', function() {
$(this).slideUp(200);
});
or even:
$alertdiv.live('click', function() {
$(this).slideUp(200);
});
I think this may be the only way to bind dynamically generated elements. I've never tried .click()
outside of the document ready function.
Edit: In addition to the above suggestion for jQuery, your css should be changed to specify a height for the div. Your height of 0 will cause it to render, technically, and possibly slide up. But, you won't be able to see it because it is 0 pixels tall at point 0,0.
alert($alertdiv.text(message)); is also setting $alertdiv's text to messasge and returning $alertdiv in order to support jQuery's chaining. What you're looking for is $alertdiv.text(), which would return the text inside $alertdiv.
Also, why are you creating that div dynamically? Is there any reason that you can't just have it on the page and hide/show it via slideUp()/slideDown()?
To insert a <div>
dynamically you can use this
$('<div>Test</div>').insertAfter('.inner');
//to insert after an element with class inner
or better
$("#myparent").html("<div id='mynewdiv'>hi</div>");
精彩评论