我需要从某个跨度中删除几个字符。我将特别需要针对 itemprop 属性。完整的元素是:
<span itemprop="dateVehicleFirstRegistered" class="wpcm-vehicle-data">03-1973</span>
目前,它显示 03-1973,而我只需要 1973。我想如果我无法弄清楚它在插件中的设置位置,我可以简单地使用 substring 删除前 3 个字符以仅显示 1973 .
当然,年份会根据用户输入的内容而有所不同,因此需要针对 itemprop 而不仅仅是这个特定案例。
我已经有一段时间没有使用 jQuery 了。我目前的尝试是:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('span[itemprop="dateVehicleFirstRegistered"]').substring(3);
});
</script>
但是我收到一条错误消息,提示它不是一个函数。错误:
(index):494 Uncaught TypeError: jQuery(...).substring is not a function
at HTMLDocument.<anonymous> ((index):494)
at i (jquery.js?ver=1.12.4:2)
at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4:2)
at Function.ready (jquery.js?ver=1.12.4:2)
at HTMLDocument.K (jquery.js?ver=1.12.4:2)
可能遗漏了一些明显的东西。有什么建议吗?
最佳答案
jQuery('span[itemprop="dateVehicleFirstRegistered"]')
不返回字符串,因此在其上使用字符串方法将不起作用。您需要将该跨度的内容作为字符串获取,然后对其使用 substring 方法,然后使用新值重置 span
的内容。
此外,使用each
循环对每个实例进行更改:
jQuery(document).ready(function(){
jQuery('span[itemprop="dateVehicleFirstRegistered"]').each(function() {
let myText = jQuery(this).text();
myText = myText.substring(3);
jQuery(this).text(myText);
});
});
关于jquery - 使用 jQuery 修剪 itemprop 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55244122/