[英]How to convert an element into 2 elements with jquery
I have this element: 我有这个元素:
<h4>username (role) on 26 Nov 2018 20:39:42 +00:00:</h4>
and I need it to be like this: 我需要它像这样:
<h4>username (role)</h4>
<p>on 26 Nov 2018 20:39:42 +00:00:</p>
There will always be 2 words in the <h4>
element, but those words will vary. <h4>
元素中总会有2个单词,但这些单词会有所不同。 The <p>
element will be dynamically updated to the current date and time, but will always start with "on" and end with "00:". <p>
元素将动态更新为当前日期和时间,但始终以“on”开头,以“00:”结束。
How can I achieve this outcome? 我怎样才能达到这个目的? I'm using jQuery but am fairly new to it, so I can't seem to find the right approach.
我正在使用jQuery,但它相当新,所以我似乎无法找到正确的方法。
You can split on on
and then use after()
to create a new p
: 您可以在分割
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>
It will be better to fix this kind of cases without the use of the JS code, but if you don't have access to the source and you really need a JS soltion, check this one: 最好在不使用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>
// 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>
This answer utilizes regex and jquery to get the current header and then create the new elements. 这个答案利用正则表达式和jquery来获取当前头,然后创建新元素。
Quick and dirty solution: 快速而肮脏的解决方
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.