【问题标题】:jquery function if param exist in url如果参数存在于 url 中,则 jquery 函数
【发布时间】:2016-06-21 08:28:02
【问题描述】:

你好,我有这个代码:

if ($('.page-id-6 #cherry-posts-list-1 .item-2 .post-title a').text().length > 28);
{
    $('.page-id-6 #cherry-posts-list-1 .item-2 .post-title a').text( $('.page-id-6 #cherry-posts-list-1 .item-2 .post-title a').text().substring(0,28));
}

它运行良好,但我还需要将子字符串设置为 35,前提是 url 中有:“/en/”。

默认为 28,仅当 url 中存在“/en/”时为 35。

可以帮帮我吗? 谢谢

【问题讨论】:

    标签: jquery url substring


    【解决方案1】:

    您可以使用String.prototype.indexOf 方法来检查段是否存在:

    $('.page-id-6 #cherry-posts-list-1 .item-2 .post-title a').text(function(_, text) {
       var len = this.getAttribute('href').indexOf('/en/') > -1 ? 35 : 28;
       // the subsequent lines can be replaced with `return text.substring(0, len);`
       if ( text.length > len ) {
         return text.substring(0, len);
       }
       return text;
    });
    

    【讨论】:

      【解决方案2】:

      这是使用 Javascript 检查 URL 的最佳方式

       if (window.location.href.indexOf("/en/") > -1) {
            // do stuff
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-29
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        • 2019-07-28
        • 2017-03-07
        • 1970-01-01
        • 2023-03-08
        相关资源
        最近更新 更多