【问题标题】:How could you with jQuery select the number at the end of the pathline?您如何使用 jQuery 选择路径末尾的数字?
【发布时间】:2010-09-23 00:17:01
【问题描述】:

我正在尝试使用 jquery 在 href 末尾获取 15

 <a class="ajax" href="/organizations/1/media/galleries/15">Silly Gangs</a>

有什么想法吗?

【问题讨论】:

    标签: jquery html css-selectors


    【解决方案1】:

    你不需要jQuery,只需要普通的 JavaScript:

    var href = someLinkElement.href;
    var lastIndex = href.lastIndexOf('/') + 1;
    var lastComponent = href.substring(lastIndex);
    

    【讨论】:

    • 同意 jQuery 是矫枉过正,直到你有一个你想要使用的这些东西的列表......然后$(elements).each(...); 变得非常方便
    【解决方案2】:

    你可以这样做:

    var Value=$("a.ajax").attr("href").split("/").pop();
    

    比使用正则表达式要快。

    Example in action.

    【讨论】:

    • 因为它是一组画廊,我想一次会有很多这样的画廊。你的只抓住其中一个。只是想我会指出这一点。 〜另外,我喜欢我们俩如何设法同时发布大致相同的答案;)
    • OP 没有表明不止一个。 IE。 “我正在尝试在 the href 的末尾获取 15”。
    • +1 表示split()/pop() 方法。这比使用 lastIndexOf()/substring() 更耗费资源,但对于大多数 UI 代码来说,这几乎不会产生任何明显的差异。
    【解决方案3】:
    var num = $("a.ajax").attr("href").replace(/.*\/(\d+)$/, "$1");
    

    正则表达式的解释:

    .*           # anything (this runs right to the end of the string)
    \/           # a slash (backtracks to the last slash in the string)
    (\d+)        # multiple digits (will be saved to group $1)
    $            # end-of-string anchor (ensures correct match)
    

    replace() 调用将用结尾的数字替换整个输入字符串,无论它可能是什么。如果末尾没有数字,它将返回""

    哦,这里的额外好处是更多地使用了 jQuery,根据需要进行修改:

    $("a.ajax").each(function () {
      $(this).data("num", /* store in data for later re-use */
        $(this).attr("href").replace(/.*\/(\d+)$/, "$1")
      );
    });
    

    【讨论】:

    • 你是绝地武士。这现在甚至是一个记录在案的 jQuery 方法并且它可以工作。怎么不是“实际上替换任何东西”?
    • @Trip: attr("href") 返回一个字符串,基本上是属性值的副本。 replace() 对该副本进行操作。要替换实际的 href 值,我需要调用 attr("href", newValue),但这不会发生在这里。
    【解决方案4】:
    $(".ajax").each( function() {
      var lastElementOfHREF = $(this).attr("href").split("/").pop();
      // now you do something here with this lastElement...
    });
    

    【讨论】:

      猜你喜欢
      • 2016-04-13
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 2018-12-04
      • 2018-10-31
      相关资源
      最近更新 更多