[英]Remove last comma inside a div in a WordPress page using JS/jQuery
I'm new to JS/jQuery!我是 JS/jQuery 的新手!
I have a plugin who create entries when members submit a form, entries are displayed in a WordPress page.我有一个插件,它在成员提交表单时创建条目,条目显示在 WordPress 页面中。
I want to remove the last comma from div critselect
in a WordPress page.我想从 WordPress 页面的 div
critselect
中删除最后一个逗号。 So, after CRM
comma must to be removed.所以,
CRM
后的逗号必须要去掉。
What I'm doing wrong?我做错了什么? I'm beginner!
我是初学者!
/*This code are in a WordPress page, on top page*/ jQuery(function($) { $('.critselect').each(function() { var xContents = $(this).contents(); xContents[xContents.length - 1].nodeValue = ""; }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!--This code are in a WordPress page --> <div class="critselect"> <h4>MY ENTRIES</h4> Marketing, Retails / Call center, Office / Back-office / CRM, </div>
jQuery(function($) {
$('.critselect').each(function() {
var xContents = $(this).html();
var lastCommaPos = xContents.lastIndexOf(',');
$(this).html(xContents.substring(0, lastCommaPos));
});
});
var div = document.getElementsByClassName('critselect')[0];
var str = div.innerHTML;
var position = str.lastIndexOf(",")+1;
var div.innerHTML = str.substring(0,position - 1) + str.substring(position, str.length);
If there might be whitespace at the end and/or there might not be a trailing comma at all, a regular expression is a good way to go.如果末尾可能有空格和/或可能根本没有尾随逗号,则正则表达式是一个不错的选择。
document.querySelectorAll('.critselect').forEach(el => {
el.innerHTML = el.innerHTML.replace(/,\s*$/, '');
});
It's even better if you place the list in its own element.如果您将列表放在它自己的元素中,那就更好了。 That way you can be certain you're only editing the list, not anything else in the
div.critselect
.这样你就可以确定你只是在编辑列表,而不是
div.critselect
任何其他div.critselect
。
<div class="critselect">
<h4>MY ENTRIES</h4>
<span>Marketing, Retails / Call center, Office / Back-office / CRM,</span>
</div>
document.querySelectorAll('.critselect > span').forEach(el => {
el.innerHTML = el.innerHTML.replace(/,\s*$/, '');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.