【问题标题】:Slicing the last two characters off a jquery variable从 jquery 变量中切出最后两个字符
【发布时间】:2017-01-08 00:37:47
【问题描述】:

所以我找到了一个脚本,它可以根据下拉菜单中的选择来呈现图像。

但是这个脚本或其他地方将这些 |0 字符附加到图像源的末尾。

这是jquery中的脚本

<script type="text/javascript">

 jQuery(document).ready(function($){

var dropdown = '#input_1_10'; // the ID of your dropdown feild
var imageContainer = '#swatches'; // the id of the div which contains your image

$(dropdown).change(function(){
    var value = $(this).val();
    jQuery(imageContainer).html('<img src="'+value+'" alt="" />'); 
});

});

   </script>

这是我从检查元素窗口看到的

<img src="http://www.whiskey3defensesolutions.com/wp-content/uploads/2016/11/1-Arctic-White.jpg|0" alt="">

这发生在我尝试与下拉选项链接的每张图片上

所以我想做的是切掉|0,但我不知道怎么做

这是在运行 Woocommerce、Woocommerce Gravity forms Add-on 和 Gravity forms plugin 的 wordpress 网站上。

【问题讨论】:

    标签: jquery wordpress gravity-forms-plugin


    【解决方案1】:

    你可以使用.split("|")来分割字符串。

    $(document).ready(function($){
      var dropdown = '#input_1_10'; // the ID of your dropdown feild
      var imageContainer = '#swatches'; // the id of the div which contains your image
      $(dropdown).change(function(){  
        var value = $(this).val().split("|")[0];   
        $(imageContainer).html('<img src="'+value+'" alt="" />'); 
      });    
    });
    

    【讨论】:

    • 感谢您的回复
    • 当我复制并粘贴您的代码(仍在脚本标签之间)时,它不起作用。但是当我只是将拆分的 sn-p 粘贴到原始图像中时效果最好,我发现一些图像被附加了 3 个字符,因此切片功能仅适用于某些图像。这对每个人都有效。
    • 是的,无论“|”后面有多少个字符,它都会起作用。我完全不知道为什么它对你不起作用,因为它应该起作用。如果您有另一个脚本,请确保将代码(不带 document.ready() )放入另一个脚本中。也不要使用属性来设置图像的宽度/高度。改用 $(imageContainer).width(75) 和 $..height(74) 或一个类。
    【解决方案2】:

    尝试使用slice js 函数。它可以根据您的需要切割字符串。我们将使用它来剪切字符串的最后 2 个字符。

    <script type="text/javascript">
    
         jQuery(document).ready(function($){
    
        var dropdown = '#input_1_10'; // the ID of your dropdown feild
        var imageContainer = '#swatches'; // the id of the div which contains your image
    
        $(dropdown).change(function(){
            var value = $(this).val();
            value = value.slice(0,-2)  //<--this should be cutting it
            jQuery(imageContainer).html('<img src="'+value+'" alt="" />'); 
        });
    
        });
    
    </script>
    

    【讨论】:

    • 这很好用,我猜我脑子里放了个屁。谢谢
    • @michaelupton 看起来这是我的第一个正确答案所以我很高兴它帮助了你哈哈:)
    • @michaelupton 不要忘记点击最佳答案!哈哈
    【解决方案3】:

    您也可以使用Regex 替换文字

    var url = 'http://.../1-Arctic-White.jpg|0';
    
    var newUrl = url.replace(/\|.*?$/, '');
    
    console.log(newUrl);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-17
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      相关资源
      最近更新 更多