Using jQuery to trim itemprop attribute

问题: I need to shave off a few characters from a certain span. I'll specifically need to target the itemprop attribute. The full element is: <span itemprop="dateVehicleFirs...

问题:

I need to shave off a few characters from a certain span. I'll specifically need to target the itemprop attribute. The full element is:

<span itemprop="dateVehicleFirstRegistered" class="wpcm-vehicle-data">03-1973</span>

Currently, it's displaying 03-1973, when I only need 1973. I figured if I couldn't work out where this was being set in the plugin, I could simply use substring to remove the first 3 characters to just show 1973.

The year, of course, varies depending on what the user enters, hence needing to target the itemprop rather than just this one specific case.

It's been a while since I used jQuery. My current attempt is:

<script type="text/javascript">
jQuery(document).ready(function(){
        jQuery('span[itemprop="dateVehicleFirstRegistered"]').substring(3);
    });
</script>

However i'm getting an error saying it isn't a function. The error:

(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)

Likely missing something obvious. Any suggestions?


回答1:

jQuery('span[itemprop="dateVehicleFirstRegistered"]') doesn't return a string, so using string methods on it won't work. You need to get the contents of that span as a string, then use the substring method on it, then reset the contents of the span with the new value.

Additionally, use an each loop to make the change to every instance:

jQuery(document).ready(function(){
    jQuery('span[itemprop="dateVehicleFirstRegistered"]').each(function() {
        let myText = jQuery(this).text();
        myText = myText.substring(3);
        jQuery(this).text(myText);
    });
});

回答2:

You can use split function to get year.

console.log($('span[itemprop="dateVehicleFirstRegistered"]').text().split("-")[1]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span itemprop="dateVehicleFirstRegistered" class="wpcm-vehicle-data">03-1973</span>

  • 发表于 2019-03-22 23:58
  • 阅读 ( 216 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除