【问题标题】:trying to remove a character from a string works in the console but not at the page尝试从字符串中删除字符在控制台中有效,但在页面中无效
【发布时间】:2016-09-09 11:43:35
【问题描述】:

我正在尝试使用以下 jquery sn-p 从文本链接中删除 - 字符:

$('.footer-widget li a').each(function(){
    var str = $(this).text();  
    str = str.replace(/-/g, "");  
    console.log(str); 
});

在控制台中角色将被删除,但不会在页面本身。 请参阅My site 的左页脚小部件。

有人可以帮忙吗?

【问题讨论】:

  • 为什么不在服务器端做呢?事实上,为什么你必须删除它们?如果您不想要它们,请不要添加它们
  • 似乎错误消失了。有任何答案对您有帮助吗?请标记为已接受。

标签: javascript jquery html string text


【解决方案1】:

您没有更新页面上的文本,请使用text() 更新每个元素

试试:

$(document).ready(function() {
    $('.footer-widget li a').each(function(i,v){
              var str = $(this).text();  
              str = str.replace(/-/g, "");  
              console.log(str); 
              $(v).text(str);
          });
});

【讨论】:

  • 发表于 11:46:13
  • 取决于你的时钟 :))
【解决方案2】:

使用带有回调的 text() 方法迭代元素并且可以根据旧值更新文本。

$('.footer-widget li a').text(function(i,v){
    return v.replace(/-/g, "");  
});

【讨论】:

    【解决方案3】:

    试试这个:

    $('.footer-widget li a').each(function(){
              var str = $(this).text();  
              $(this).text(str.replace(/-/g, "");
              console.log(str); 
          });
    

    【讨论】:

    • 发表于 11:46:21
    【解决方案4】:

    你做对了,但忘记了将值设置回它。

    $(".footer-widget li a").text(str);
    

    【讨论】:

    • 发表于 11:46:26
    【解决方案5】:

    如果您打开浏览器控制台(或某些 Web 开发工具),您会在脚本中看到错误

    TypeError: $(...).replace is not a function
            $('.footer-widget li a').replace(/\-/g, '+');
    

    这可能有很多可能的原因,但大多数可能是因为 jQuery 库尚未初始化。因此所有使用 jQuery 的脚本都应该用

    $(document).ready(function() {
        ....
    });
    

    更重要的是您的页面中似乎没有包含 jQuery 核心库,只有一些 UI 插件。如果我打开浏览器控制台,我也不能使用 jQuery。您可能有一些改进的浏览器控制台,其中包含 jQuery。

    我发现你的 jQuery 库被注释掉了

    <!-- <script type='text/javascript' src='http://fhchp.de/wp-includes/js/jquery/jquery.js?ver=1.12.4'></script> -->
    

    【讨论】:

      猜你喜欢
      • 2017-02-02
      • 2019-12-08
      • 1970-01-01
      • 2018-06-06
      • 2013-12-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 2011-05-13
      相关资源
      最近更新 更多