简体   繁体   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?

Thanks for taking time to help out. 感谢您抽出宝贵时间为您提供帮助。 CoffeeScript version is 1.3.3; CoffeeScript版本是1.3.3; jQuery version is from Rails 3.2.8 jquery-rails gem 2.1.3. jQuery版本来自Rails 3.2.8 jquery-rails gem 2.1.3。

I have an array of poems with their respective links stored in $poems_for_year_hrefs. 我有一系列诗歌,它们各自的链接存储在$ poems_for_year_hrefs中。 I am able to grab the index of the elements in $poems_for_year_hrefs using $.each() and storing in poemUrls. 我可以使用$ .each()获取$ poems_for_year_hrefs中元素的索引并将其存储在poemUrls中。

The page's next link, when clicked on, is used to increment the index of poemUrls to the next element and update the $next_link's href attribute. 单击页面的下一个链接时,该链接用于将poemUrl的索引增加到下一个元素,并更新$ next_link的href属性。 If the index exceeds the length of the poemUrls, then the index is set back to 0 to give the first element in the array. 如果索引超过poemUrls的长度,则将索引设置回0以给出数组中的第一个元素。

The page's previous link, when clicked on, is used to obtain the next element in the $poems_for_year_hrefs by decrementing the current index in poemUrl by 1. Then it updates the $prev_link's href attribute. 单击页面上的上一个链接时,该链接用于通过将poemUrl中的当前索引减1,从而获得$ poems_for_year_hrefs中的下一个元素。然后,更新$ prev_link的href属性。 If the current index is less than or equal to 0 it goes to the last element in the poemUrls array. 如果当前索引小于或等于0,则转到poemUrls数组中的最后一个元素。

Here is the CoffeeScript code: 这是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')}"

and the HTML: 和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>

I am using Ajax to make updates to the main-poem div. 我正在使用Ajax更新主诗div。 If I click on the 2nd poem (id=17) in poems-for-year div, the main-poem div will update, showing the contents of the 2nd poem (id=17). 如果单击年份诗歌div中的第二首诗(id = 17),则主诗div将更新,显示第二首诗(id = 17)的内容。 If I click on the next link, the first poem that's indexed in the poemUrls at position 0 is returned. 如果单击下一个链接,则返回在poemUrls中位置0索引的第一首诗。 Then I click next and the poem in position 1 of the poemUrls is returned and then next again and the position 2 is returned moves along like it should. 然后单击“下一步”,返回poemUrls位置1的诗,然后再次返回位置2,其返回值应与它一样。 Once I reach the end of the array, I click the next link to cycle the index count back to 0 to reach the beginning of the poemUrls array, I need to click next twice. 到达数组末尾后,单击下一个链接以将索引计数循环回0以到达poemUrls数组的开头,我需要单击下一步两次。 The first click does nothing. 第一次单击不会执行任何操作。

The same issue is experienced, if I select the 3rd poem, then click the previous link. 如果我选择第三首诗,也会遇到相同的问题,然后单击上一个链接。 The index starts at 0 and then returns the 1st position of the poemUrl array. 索引从0开始,然后返回poemUrl数组的第1个位置。 Click previous, goes through array decrementing the index by one. 单击上一个,遍历数组将索引减一。 Gets to the 1st element, then I need to click previous twice to get to the last position in the array. 获取第一个元素,然后我需要单击上一个两次以获取数组中的最后一个位置。

Why do I need to click it twice? 为什么需要单击两次? Is it a variable that loses context? 它是失去上下文的变量吗?

* Also how can I pass the reference of the currently selected element to $next_link.click so it knows what the current element selected is and can get the proper next element rather than starting at 0? * 另外,如何将当前选定元素的引用传递给$ next_link.click,以便它知道当前选定的元素是什么,并且可以获得正确的下一个元素而不是从0开始? In other words, if I click on the 2nd poem (id=17) in poems-for-year, how can I get $next_link.click to return the 3rd poem (id=18), or if I click previous get $prev_link.click to return the 1st poem (id=16)?* 换句话说,如果我单击一年诗歌中的第二首诗(id = 17),如何获得$ next_link.click以返回第三首诗(id = 18),或者如果单击上一首诗则获得$ prev_link .click返回第一首诗(id = 16)?*

The CoffeeScript compiled to JavaScript: 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')));
  });
});

Edit 编辑

    $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}"

Testing results: The poemUrls array contains these: /poetry/2011/1st%20poem%20title%202011?id=19,/poetry/2011/2nd%20poem%20title%202011?id=20,/poetry/2011/3rd%20poem%20title%202011?id=21 测试结果: 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

Clicked on a poem title with index of 2 (last poem in array containing 3 poems) When I call $prev_link.click, prevPoemUrl is /poetry/2011/3rd%20poem%20title%202011?id=21 (last poem in array) When I call $prev_link_click, prev_link href is undefined 单击索引为2的诗标题(数组中包含3首诗的最后一首诗)当我调用$ prev_link.click时,prevPoemUrl为/ poetry / 2011 / 3rd%20poem%20title%202011?id = 21(数组中的最后一首诗)当我调用$ prev_link_click时,prev_link href是未定义的

I click on the last poem again: Clicked on a poem title with index of 2 (last poem) 我再次单击最后一首诗:单击索引为2的一首诗标题(最后一首诗)

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

When I call $next_link_click, next_link href is: undefined 当我呼叫$ next_link_click时,next_link href是:undefined

Seems that the prev returns the last poem indexed and next returns the first poem indexed Thanks for your help! 似乎上一个返回索引的最后一首诗,下一个返回索引的第一首诗谢谢您的帮助!

You have an off-by-one error . 您有一个错误的错误 The errors are at, 错误在于

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

In your example, poemUrls.length is 3 , and since JavaScript arrays are zero-based (they start counting at zero) the valid indexes are 0, 1, and 2 . 在您的示例中, poemUrls.length3 ,并且由于JavaScript数组基于零(它们从零开始计数),所以有效索引为0、1和2 The first snippet will let the index get to 3 before setting it to 0 . 第一个片段将使索引在设置为0之前变为3 The second snippet will set the index to 3 when it reaches 0 . 第二个片段将在索引到达0时将其设置为3 The corrected code is, 正确的代码是

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

Edit 编辑

Addressing the second question, if you want to access the siblings of the current poem, you can use your array and index structure. 解决第二个问题,如果您想访问当前诗歌的兄弟姐妹,则可以使用数组和索引结构。 The quick CoffeeScript solution would be, 快速的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 ]

Here's the source for getting the current position of the clicked poem, and having the next and previous link proceed accordingly. 这是获取点击诗的当前位置以及相应地进行下一个和上一个链接的来源。 It's a rough draft, but works: 这是草稿,但可以:

$(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