繁体   English   中英

如何正确到达数组的开头或结尾? 如何传递当前所选项目的参考?

[英]How do I get to the beginning or end of the array properly? How do I pass in a reference of currently selected item?

感谢您抽出宝贵时间为您提供帮助。 CoffeeScript版本是1.3.3; jQuery版本来自Rails 3.2.8 jquery-rails gem 2.1.3。

我有一系列诗歌,它们各自的链接存储在$ poems_for_year_hrefs中。 我可以使用$ .each()获取$ poems_for_year_hrefs中元素的索引并将其存储在poemUrls中。

单击页面的下一个链接时,该链接用于将poemUrl的索引增加到下一个元素,并更新$ next_link的href属性。 如果索引超过poemUrls的长度,则将索引设置回0以给出数组中的第一个元素。

单击页面上的上一个链接时,该链接用于通过将poemUrl中的当前索引减1,从而获得$ poems_for_year_hrefs中的下一个元素。然后,更新$ prev_link的href属性。 如果当前索引小于或等于0,则转到poemUrls数组中的最后一个元素。

这是CoffeeScript代码:

$(document).ready ->
    $poem_years = $('#poems-for-year ul li a')
    $poem = $('#main-poem').hide()
    $poem_years.click -> 
      $poem.eq(0).fadeIn('slow', -> 
        $poem.slideDown('slow')
     )
     console.log "Clicked on a poem title with index of #{$poem_years.index(@)}"

    $poems_for_year_hrefs = $('#poems-for-year ul li a[href]')

    index = $poems_for_year_hrefs.index(@)
    poemUrls = []
    $($poems_for_year_hrefs).each((i)->
      poemUrls[i] = $(@).attr('href')
      poemUrls.join(",")
    )
    console.log "The poemUrls array contains: #{poemUrls}"

    $next_link = $('#previous-next li a').last()
    $next_link.click ->
      if index >= poemUrls.length
        index = 0
        $next_link.attr('href', poemUrls[index]).attr('href')
      else
        index += 1
        console.log "$next_link was clicked on!"
        $next_link.attr('href', poemUrls[index]).attr('href')
        console.log "$next_link href was set to #{$next_link.attr('href')}"

    $prev_link = $('#previous-next li a').first()
    $prev_link.click ->
      if index <= 0
        index = poemUrls.length
        $prev_link.attr('href', poemUrls[index]).attr('href')
      else
        index -= 1
        console.log "$prev_link was clicked on!"
        $prev_link.attr('href', poemUrls[index]).attr('href')
      console.log "$prev_link href was set to #{$prev_link.attr('href')}"

和HTML:

    <!DOCTYPE html>
    <html>
    <head>
    <title>...</title>
    <link href="/assets/application.css?body=1" media="all" rel="stylesheet" type="text/css" />
    <script src="/assets/jquery.js?body=1" type="text/javascript"></script>
    <script src="/assets/jquery_ujs.js?body=1" type="text/javascript"></script>
    <script src="/assets/poetry.js?body=1" type="text/javascript"></script>
    <script src="/assets/application.js?body=1" type="text/javascript"></script>
    <meta content="authenticity_token" name="csrf-param" />
    <meta content="XcXpd5Fg50gvWP8tVLB0/HOfBxoPaTOJ9q37zArrrFo=" name="csrf-token" />
    </head>
    <body>
    <div>
    <div id="content">
    <h1>poetry</h1>
    <section id="poem-selections">
    <article id="archives">
    <nav id="archive-year-nav">
    <ul>
    <li><a href="/poetry/2011">2011</a>
    <li><a href="/poetry/2012">2012</a>
    </ul>
    </nav>

    <div id="poems-for-year">
    <ul>
    <li><a href="/poetry/2012/1st%20poem%20title?id=16" data-remote="true">1st poem   title</a>
    </li>
    <li><a href="/poetry/2012/2nd%20poem%20title?id=17" data-remote="true">2nd poem  title</a>
    </li>
    <li><a href="/poetry/2012/3rd%20poem%20title?id=18" data-remote="true">3rd poem   title</a>
    </li>
    </ul>

   </div>
   </article>

   </section>

   <section id="main">

   <article>
   <div id="main-poem">
   <h3>2nd poem title</h3>
   <p>2nd poem verse</p>
   </div>
   <nav>
   <ul id="previous-next">
   <li><a href="/poetry/2012/previous_poem/2nd%20poem%20title?id=17" data-  remote="true">previous</a></li>
   <li><a href="/poetry/2012/next_poem/2nd%20poem%20title?id=17" data-remote="true">next</a>      </li>
   </ul>
   </nav>

   </article>

   </section>
   </div>
   </body>
   </html>

我正在使用Ajax更新主诗div。 如果单击年份诗歌div中的第二首诗(id = 17),则主诗div将更新,显示第二首诗(id = 17)的内容。 如果单击下一个链接,则返回在poemUrls中位置0索引的第一首诗。 然后单击“下一步”,返回poemUrls位置1的诗,然后再次返回位置2,其返回值应与它一样。 到达数组末尾后,单击下一个链接以将索引计数循环回0以到达poemUrls数组的开头,我需要单击下一步两次。 第一次单击不会执行任何操作。

如果我选择第三首诗,也会遇到相同的问题,然后单击上一个链接。 索引从0开始,然后返回poemUrl数组的第1个位置。 单击上一个,遍历数组将索引减一。 获取第一个元素,然后我需要单击上一个两次以获取数组中的最后一个位置。

为什么需要单击两次? 它是失去上下文的变量吗?

* 另外,如何将当前选定元素的引用传递给$ next_link.click,以便它知道当前选定的元素是什么,并且可以获得正确的下一个元素而不是从0开始? 换句话说,如果我单击一年诗歌中的第二首诗(id = 17),如何获得$ next_link.click以返回第三首诗(id = 18),或者如果单击上一首诗则获得$ prev_link .click返回第一首诗(id = 16)?*

CoffeeScript编译为JavaScript:

$(document).ready(function() {
  var $next_link, $poem, $poem_years, $poems_for_year_hrefs, $prev_link, index, poemUrls;
  $poem_years = $('#poems-for-year ul li a');
  $poem = $('#main-poem').hide();
  $poem_years.click(function() {
    $poem.eq(0).fadeIn('slow', function() {
      return $poem.slideDown('slow');
    });
    return console.log("Clicked on a poem title with index of " + ($poem_years.index(this)));
  });
  $poems_for_year_hrefs = $('#poems-for-year ul li a[href]');
  index = $poems_for_year_hrefs.index(this);
  poemUrls = [];
  $($poems_for_year_hrefs).each(function(i) {
    poemUrls[i] = $(this).attr('href');
    return poemUrls.join(",");
  });
  console.log("The poemUrls array contains: " + poemUrls);
  $next_link = $('#previous-next li a').last();
  $next_link.click(function() {
    if (index >= poemUrls.length) {
      index = 0;
      return $next_link.attr('href', poemUrls[index]).attr('href');
    } else {
      index += 1;
      console.log("$next_link was clicked on!");
      $next_link.attr('href', poemUrls[index]).attr('href');
      return console.log("$next_link href was set to " + ($next_link.attr('href')));
    }
  });
  $prev_link = $('#previous-next li a').first();
  return $prev_link.click(function() {
    if (index <= 0) {
      index = poemUrls.length;
      $prev_link.attr('href', poemUrls[index]).attr('href');
    } else {
      index -= 1;
      console.log("$prev_link was clicked on!");
      $prev_link.attr('href', poemUrls[index]).attr('href');
    }
    return console.log("$prev_link href was set to " + ($prev_link.attr('href')));
  });
});

编辑

    $next_link = $('#previous-next li a').last()
    $next_link.click ->
      nextPoemUrl = poemUrls[ if index >= poemUrls.length - 1 then 0 else index + 1 ]
      console.log "When I call $next_link_click, nextPoemUrl is: #{nextPoemUrl}"
      $next_link.attr('href', nextPoemUrl).attr('href')
      console.log "When I call $next_link_click, next_link href is: #{$next_link.href}"

    $prev_link = $('#previous-next li a').first()
    $prev_link.click ->
      prevPoemUrl = poemUrls[ if index <= poemUrls.length - 1 then 0 else index - 1 ]
      console.log "When I call $prev_link.click, prevPoemUrl is #{prevPoemUrl}"
      $prev_link.attr('href', prevPoemUrl).attr('href')
      console.log "When I call $prev_link_click, prev_link href is #{$prev_link.href}"

测试结果: poemUrls数组包含以下内容:/ poetry / 2011 / 1st%20poem%20title%202011?id = 19,/ poetry / 2011 / 2nd%20poem%20title%202011?id = 20,/ poetry / 2011 / 3rd% 20poem%20title%202011?id = 21

单击索引为2的诗标题(数组中包含3首诗的最后一首诗)当我调用$ prev_link.click时,prevPoemUrl为/ poetry / 2011 / 3rd%20poem%20title%202011?id = 21(数组中的最后一首诗)当我调用$ prev_link_click时,prev_link href是未定义的

我再次单击最后一首诗:单击索引为2的一首诗标题(最后一首诗)

当我呼叫$ next_link_click时,nextPoemUrl是:/ poetry / 2011 / 1st%20poem%20title%202011?id = 19

当我呼叫$ next_link_click时,next_link href是:undefined

似乎上一个返回索引的最后一首诗,下一个返回索引的第一首诗谢谢您的帮助!

您有一个错误的错误 错误在于

if index >= poemUrls.length
    index = 0
...
if index <= 0
    index = poemUrls.length

在您的示例中, poemUrls.length3 ,并且由于JavaScript数组基于零(它们从零开始计数),所以有效索引为0、1和2 第一个片段将使索引在设置为0之前变为3 第二个片段将在索引到达0时将其设置为3 正确的代码是

if index >= poemUrls.length - 1
    index = 0
...
if index <= 0
    index = poemUrls.length - 1

编辑

解决第二个问题,如果您想访问当前诗歌的兄弟姐妹,则可以使用数组和索引结构。 快速的CoffeeScript解决方案是

prevPoemUrl = poemUrls[ if index <= 0 then poemUrls.length - 1 else index - 1 ]
nextPoemUrl = poemUrls[ if index >= poemUrls.length - 1 then 0 else index + 1 ]

这是获取点击诗的当前位置以及相应地进行下一个和上一个链接的来源。 这是草稿,但可以:

$(document).ready ->
    $poem_years = $('#poems-for-year ul li a')
    $poem = $('#main-poem').hide()
    $poem_years.click -> 
      $poem.eq(0).fadeIn('slow', -> 
        $poem.slideDown('slow')
      )
      console.log "Clicked on a poem title with index of #{$poem_years.index(@)}" # <-- where gets current index of clicked poem title!
      $poems_for_year_hrefs = $('#poems-for-year ul li a[href]')
      index = $poem_years.index(@) # <-- Assign the current reference to the index variable
      poemUrls = []
      $($poems_for_year_hrefs).each((i)->
        poemUrls[i] = $(@).attr('href')
        poemUrls.join(",")
      )

      console.log "The poemUrls array contains these: #{poemUrls}"

      $prev_link = $('#previous-next li a').first()
      $prev_link.click ->
       console.log "the prevPoemUrl is: #{poemUrls[index]}"
       if index <= 0
         index = poemUrls.length - 1
         $prev_link.attr('href', poemUrls[index]).attr('href')
         $('#main-poem').hide().fadeIn('slow')
         console.log "$prev_link href when <= poemUrls.length was set to #{$prev_link.attr('href')}"
         console.log "The poemUrls when <= poemUrls.length is: #{poemUrls[index]}"
       else
         index -= 1
         console.log "$prev_link was clicked on!"
         $prev_link.attr('href', poemUrls[index]).attr('href')
         $('#main-poem').hide().fadeIn('slow')
         console.log "$prev_link href was set to #{$prev_link.attr('href')}"   
         console.log "The poemUrls poemUrls.length is: #{poemUrls[index]}"

      $next_link = $('#previous-next li a').last()
      $next_link.click ->
        if index >= poemUrls.length - 1
          index = 0
          $next_link.attr('href', poemUrls[index]).attr('href')
          $('#main-poem').hide().fadeIn('slow')
          console.log "$next_link href when >= poemUrls.length was set to #{$next_link.attr('href')}"
          console.log "The poemUrl when >= poemUrls.length is: #{poemUrls[index]}"
        else
          index += 1
          console.log "$next_link was clicked on!"
          $next_link.attr('href', poemUrls[index]).attr('href')
          console.log "$next_link href was set to #{$next_link.attr('href')}"
          console.log "The poemUrls when < poemUrls.length is: #{poemUrls[index]}"
          $('#main-poem').hide().fadeIn('slow')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM