【问题标题】:Get part of a href path using jQuery使用 jQuery 获取 href 路径的一部分
【发布时间】:2017-03-03 20:48:15
【问题描述】:

如果我想从列表中的 href 获取日期(例如:2016-12-21),你会怎么做?然后取该值并将其放入<li>

<ul id="xdesc" class="">

    <li class="">
      2016-12-21
       <div class="">
           <a class="hs-rss-title" href="http://domain.com/events/womens-event-2016-12-21?__hstc=233546881.1c39d8c7bec9e076de1b637bf5317294.1475698351504.1477050663648.1477054875380.25&amp;__hssc=233546881.1.1477054875380&amp;__hsfp=1945213963"><span>Event 2 Women's Event</span></a>
           </div>
        </li>



    <li class="hs-rss-item">
      2016-03-21
       <div class="hs-rss-item-text">
           <a class="hs-rss-title" href="http://domain.com/events/mens-event-2016-03-21?__hstc=233546881.1c39d8c7bec9e076de1b637bf5317294.1475698351504.1477050663648.1477054875380.25&amp;__hssc=233546881.1.1477054875380&amp;__hsfp=1945213963"><span>Event 1 Men's Event</span></a>

        </div>

    </li>

</ul>

【问题讨论】:

标签: jquery


【解决方案1】:

假设您的 URL 列表中有一个日期采用您提供的格式,您可以使用正则表达式:

var pattern = /\d{4}-\d{2}-\d{2}/;
var string = "http://domain.com/event/name-event-2016-12-21?__hstc=233546881.1c...";
var result = string.match(pattern);

输出:

Array [ "2016-12-21" ]

【讨论】:

    【解决方案2】:

    首先,您应该为链接添加一个 id,以便能够从 jquery 访问它们中的每一个:

    <ul id="list">
      <li>
        <a id="link1" href="..."><span>Event 1</span></a>
      </li>
      <li>
        <a id="link2" href="..."><span>Event 2</span></a>
      </li>
    </ul>
    

    然后在jquery中写下这段代码:

    // Get the href from link with id='link1'
    var mylink = $("#link1").attr('href'); 
    
    // Search the link for a pattern in this form YYYY-MM-DD
    var date = mylink.match(/[0-9]{4}[-][0-9]{2}[-][0-9]{2}/);
    
    // Now the variable date is equal to the date from the link,
    // or to null if date was not found in link. You can test it with alert.    
    alert(date);
    

    在上面的代码中,正则表达式用于从链接中获取日期。如果您想了解更多关于正则表达式的信息,请访问此链接:http://www.w3schools.com/jsref/jsref_obj_regexp.asp

    我在研究中使用的 Stackoverflow 问题: get href attribute on jQuery, Javascript date regex DD/MM/YYYY

    我希望这会有所帮助。

    【讨论】:

    【解决方案3】:

    哦,好的。然后你可以使用 .each() 函数和 .find() 函数。

    $( "#xdesc li" ).each(function( index ) {
      mylink = $(this).find('div').find('a').attr('href'); 
      date = mylink.match(/[0-9]{4}[-][0-9]{2}[-][0-9]{2}/);
      $(this).text(date);
    });
    

    .每个文档:https://api.jquery.com/each/

    .查找文档:https://api.jquery.com/find/

    .text 文档:http://api.jquery.com/text/#text-text

    希望这次能帮到你:)

    【讨论】:

      猜你喜欢
      • 2010-12-28
      • 2020-07-27
      • 2011-10-20
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 2021-10-01
      相关资源
      最近更新 更多