[英]Insert <span> in <p> element
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? 这有可能通过javascript函数吗? / or jQuery.
/或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. 哦是的,p元素有一个ID,p元素内的文本是可变的,但总是由2个单词组成。 I want a span around the last word of the text by a javascript function.
我希望通过javascript函数绕过文本的最后一个单词。
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: 或者(正如您在评论中所说,您希望保留现有内容,但是在一个
span
包装最后一个单词,您可以这样做:
var newHTML = $("#pId").html().replace(" ", " <span>");
$("#pId").html(newHTML).append("</span>");
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
返回字符串
$("document").ready(function(){
$("p").append("<span>world</span>");
});
随着JQuery追加
$("#paragraphId").append('<span>Text in span</span>');
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.