简体   繁体   English

<span>在</span>插入 <p> <span>元件</span>

[英]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函数绕过文本的最后一个单词。

Try this 试试这个

var txt = "Hello bye";
var dataArr = txt.split(' ');

var paragraph = document.getElementById("pid");
paragraph.innerHTML = dataArr[0]+ " <span>"+dataArr[1]+"</span>";

Here is a demo 这是一个演示

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>");

DEMO DEMO

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);
});

Demo 演示

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.

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