如何使用jQuery将一个元素转换为2个元素

时间:2018-11-29 15:27:07

标签: javascript jquery html

我有这个元素:

<h4>username (role) on 26 Nov 2018 20:39:42 +00:00:</h4>

我需要这样:

<h4>username (role)</h4>
<p>on 26 Nov 2018 20:39:42 +00:00:</p>

<h4>元素中始终有2个单词,但是这些单词会有所不同。 <p>元素将动态更新为当前日期和时间,但始终以“ on”开头,以“ 00:”结尾。

我如何实现这一结果?我使用的是jQuery,但它还很陌生,因此我似乎找不到正确的方法。

4 个答案:

答案 0 :(得分:2)

您可以在on上拆分,然后使用after()创建新的p

$('h4').each(function() {  // use an each so it will work if there are multiple on a page
  var $h4 = $(this),
    text = $h4.text(),
    textParts = text.split(' on');   // split on ` on`

  if (textParts.length == 2) {       // only update if there is a paragraph
    $h4.text(textParts[0]).after('<p>on ' + textParts[1] + '</p>');  // update the h4 text and put the new paragraph after it
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>username (role) on 26 Nov 2018 20:39:42 +00:00:</h4>

答案 1 :(得分:1)

最好不使用JS代码来解决这种情况,但是如果您无权访问源代码并且确实需要JS解决方案,请检查以下情况:

var h4_p = $('h4').text().split(' on');
$('h4').text(h4_p[0]);
$('<p>on ' + h4_p[1] + '</p>').insertAfter($('h4'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>username (role) on 26 Nov 2018 20:39:42 +00:00:</h4>

答案 2 :(得分:1)

代码

// gets the header element and caches it since we use it twice
let header = $('h4');
// get header text
let headerText = header.text();
// run regex to get the items we need
let result = /(.*?) (on .*)/i.exec(headerText);
// create a new header for the first group found
let newHeader = '<h4>' + result[1] + '</h4>';
// create the paragraph with the second group found
let newParagraph = '<p>' + result[2] + '</p>';
// replace the current header with the new one
header.replaceWith(newHeader + newParagraph);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>username (role) on 26 Nov 2018 20:39:42 +00:00:</h4>

说明

此答案利用正则表达式和jquery获取当前标头,然后创建新元素。

答案 3 :(得分:0)

快速而肮脏的解决方案:

var split = $("h4").text().split(" ");
var newhtml = "<h4>"+split[0]+" "+split[1]+"</h4>";
newhtml += "<p>";
for(i = 2; i < split.length;i++){
  newhtml += split[i]+" ";
}

newhtml += "</p>";

alert(newhtml)