简体   繁体   中英

How do I use jQuery to generate a paragraph with ID 'blurb' in a div?

I have a div element on my web page with ID "map" with a link to Google inside of it.

<div id="map">
    <a href="http://google.com">Google</a>
</div>

I want to use jQuery to generate a paragraph after the link with an ID of "blurb," so the HTML akin to what the Javascript produces is

<div id="map">
    <a href="http://google.com">Google</a>
    <p id="blurb"></p>
</div> 

I have been experimenting with

$('#map').append('p').attr('id', 'blurb');

to no avail.

I am open to a Javascript, but non-jQuery way to do this as well. Thank you!

This should work:

$('#map').append('<p id="blurb"></p>');

Your method was the right general idea, but was just appending the text 'p' rather than the tag <p> and the id wasn't getting set on the right object because of the way jQuery chaining works for .append() .

If you wanted to assign the id programmatically for some reason, then it's probably easier to do that this way:

$('<p>').attr('id', 'blurb').appendTo('#map');

首先,设置所有属性,然后追加。

$('<p>').attr('id', 'blurb').appendTo('#map');

Your code doesn't work for two reasons. First of all append can take text and you must distinguish between text and HTML by using a tag ( <p> ) instead of p . The other reason is that chaining means jQuery's append function will return the jQuery object that it is called on. In this case an object refering to your map element. So when you set the id you were setting the id of the map div, not of your newly create element (assuming the <p> error was fixed). Also you should use prop to set the id instead of attr, but both will probably work for id. Here is some example code:

jQuery:

$('<p>').appendTo('#map').prop('id', 'blurb');

Plain Javascript (Faster, but less legible):

var pel = document.createElement('p');
pel.id = 'blurb';
document.getElementById('map').appendChild(pel);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM