javascript 在 <p> 元素中插入 <span>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19154336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert <span> in <p> element
提问by Anoniem Anoniem
I got like;
我喜欢;
<p>Variable Text</p>
And I want to it to be;
我想要它;
<p>Variable <span>Text</span></p>
Is this possible by a javascript function? / or jQuery.
这可以通过javascript函数实现吗?/ 或 jQuery。
Oh yeah, and the p-element got an ID and the text inside the p-element is variable but always consists of 2 words. I want a span around the last word of the text by a javascript function.
哦,是的,p 元素有一个 ID,p 元素内的文本是可变的,但总是由 2 个单词组成。我想要一个 javascript 函数围绕文本的最后一个单词的跨度。
回答by iJade
回答by mattytommo
It's possible (the following assumes the p
has an ID, like you said), in it's simplest form you can just do:
这是可能的(以下假设p
有一个 ID,就像你说的那样),以最简单的形式,你可以这样做:
var paragraph = document.getElementById("pId");
paragraph.innerHTML = "Hello <span>World</span>";
Or if you want to use jQuery:
或者,如果您想使用 jQuery:
$("#pId").html("Hello <span>World</span>");
Or (as you said in comments, you want to keep the existing content, but wrap the last word in a span
, you can do:
或者(正如您在评论中所说,您想保留现有内容,但将最后一个单词包裹在 a 中span
,您可以这样做:
var newHTML = $("#pId").html().replace(" ", " <span>");
$("#pId").html(newHTML).append("</span>");
回答by Mr. Alien
I would like to share a jQuery solution, which is regardless of any words defined in your p
element
我想分享一个 jQuery 解决方案,它与您p
元素中定义的任何单词无关
$("p").html(function(){
var mystring= $(this).text().split(" ");
var lastword = mystring.pop();
return mystring.join(" ")+ (mystring.length > 0 ? " <span>"+ lastword + "</span>" : lastword);
});
In the demo above, I am splitting the string first, than am using pop
to get the last index in the array, and than am adding span
element and returning the string using join
在上面的演示中,我首先拆分字符串,然后使用pop
获取数组中的最后一个索引,然后添加span
元素并使用返回字符串join
回答by Christopher
jQuery is easier, and personally I think it's better to use than only javascript:
jQuery 更简单,我个人认为它比仅使用 javascript 更好:
jQuery:
jQuery:
$("#paragraphID").append("<span>World</span>");
HTML:
HTML:
<p id="paragraphID">Hello</p>
回答by Robby Zhi
$("document").ready(function(){
$("p").append("<span>world</span>");
});
回答by Nikhil Chavan
With JQuery append
使用 JQuery 追加
$("#paragraphId").append('<span>Text in span</span>');