简体   繁体   English

如何使用jQuery在div中生成ID为'blurb'的段落?

[英]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”,其中包含指向Google的链接。

<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 我想使用jQuery在ID为“blurb”的链接之后生成一个段落,所以HTML类似于Javascript生成的是

<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. 我对Javascript持开放态度,但非jQuery方式也是如此。 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() . 你的方法是正确的一般想法,但只是附加文本'p'而不是标记<p>并且id没有在正确的对象上设置,因为jQuery链接的方式适用于.append()

If you wanted to assign the id programmatically for some reason, then it's probably easier to do that this way: 如果你想出于某种原因以编程方式分配id,那么这样做可能更容易:

$('<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 . 首先,append可以采用文本,你必须使用标记( <p> )而不是p来区分文本和HTML。 The other reason is that chaining means jQuery's append function will return the jQuery object that it is called on. 另一个原因是链接意味着jQuery的append函数将返回它被调用的jQuery对象。 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). 因此,当您设置id时,您设置的是map div的id,而不是新创建元素的id(假设<p>错误已修复)。 Also you should use prop to set the id instead of attr, but both will probably work for id. 你也应该使用prop来设置id而不是attr,但两者都可能适用于id。 Here is some example code: 这是一些示例代码:

jQuery: jQuery的:

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

Plain Javascript (Faster, but less legible): 简单的Javascript(更快,但不太清晰):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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