简体   繁体   English

如何使用jQuery在元素中添加元素

[英]How to add element in element using jquery

I have some code like this: 我有一些这样的代码:

<p>Nuno</p>
<p>Eimes</p>

How can I manipulate it like this: 我该如何操作:

<p><a href="name/Nuno">Nuno</a></p>
<p><a href="name/Eimes">Eimes</a></p>

I've tried: 我试过了:

var name=$(this).text();
$( "p" ).each(function() {
  $(this).prepend('<a href="id/'+ $(this).text() +'"> ');
$(this).append("</a>");
});

but it results: 但结果:

<p><a href="id/Nuno"> </a>Nuno</p>
<p><a href="id/Eimes"> </a>Eimes</p>

the <a> is not inside $('p').text(); <a>不在$('p').text(); also if i change to name . 如果我name it didn't show the value. 它没有显示出价值。

$( "p" ).each(function() {
   var text = $(this).text();
   $(this).wrapInner('<a href="name/'+text+'"></a>');
 });

Live Demo 现场演示

Simple and .wrapInner() 简单和.wrapInner()

$('p').wrapInner(function(){
    return '<a href="name/' + $(this).text() + '" />' // even this.innerHTML instead of $(this).text() will do
})

Demo: Fiddle 演示: 小提琴

Once you've extracted the name, I would just rewrite the whole code within the <p></p> tags again: 提取名称后,我将再次在<p></p>标记内重写整个代码:

var name=$(this).text();
$( "p" ).each(function() {
  $(this).html('<a href="name/'+ $(this).text() +'">' + $(this).text() + '</a>');
});

You just need to grab the inner stuff, then replace everything in the tag with the new HTML: 您只需要获取内部内容,然后将标记中的所有内容替换为新的HTML:

var name=$(this).text();
$( "p" ).each(function() {
    old = $(this).html();
    $(this).html('<a href="id/'+ old +'">'+old+'</a>');
});

Fiddle 小提琴

Demo 演示

$('p').html(function () {
    return '<a href="name/' + this.innerHTML + '">' + this.innerHTML + '</a>';
});

.html() html的()

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

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