2014-06-04 21 views
0

思來測試像這樣得到它之前重複UpdateButton的點擊字段的值,但它會在瀏覽器控制檯特定按鈕類onClick之前的某些字段的值未定義?

var $prevID = $(this).prevAll('.UpdateStory').first(".storyID"); 
var $prevStory = $(this).prevAll('.UpdateStory').first(".currentStory"); 

var id = $prevID.val(); 
var story = $prevStory.val(); 

undefined值下面是HTML(客戶端+服務器端的車把。 JS)

<div id="allStories" class="allStories"> </div><!--/allStories--> 
<script id="storyTemplate" type="text/x-handlebars-template"> 

    <div class="thisness"> 
     <div class="stories"> 

     <div class="new" id="new"> 
      \{{#each stories}} 
      <div class="container-fluid"> 
       <div class="row"> 
       <div class="col-sm-4 col-sm-offset-4"> 
        <form class="updateNewStoryForm"> 
        <div class="input-group"> 
         <span class="input-group-addon"> 
         <input type="checkbox"> 
         </span> 
         <input type="hidden" class="storyID" value="\{{ _id }}"/> 
         <input type="text" class="currentStory" value="\{{ story }}"> 
         <span class="input-group-addon"> 
         <input type="button" class="UpdateStory"> 
         </span> 
        </div><!-- /input-group --> 
        </form> 
       </div><!-- /.col-lg-6 --> 
       </div><!-- /.row --> 
      </div><!-- /.container-fluid --> 
      \{{/each}} 
     </div> 

     </div> <!--/stories--> 
    </div> <!--/thisness--> 

</script> 

而這裏的AJAX。放,否則只更新第一個故事

// UpdateStory button clicks 
$(".allStories").on('click','.UpdateStory',function(e) { 

    e.preventDefault(); 
    console.log('UpdateStory clicked'); 

    // story elements for API that work for only the first item, 
    // regardless of whichever UpdateStory button is clicked 
    var id = $(".storyID").val(); 
    var story = $(".currentStory").val(); 

    console.log(id); 
    console.log(story); 

    var AjaxPostData = { 
     id : id, 
     story : story 
    }; 

    // if the story field has content 
    if (story.length != 0) { 
     console.log('there is a story: ' + story); 
     // make an ajax call 
     $.ajax({ 
     dataType: 'json', 
     data: AjaxPostData, 
     type: 'put', 
      url:"http://localhost:4200/api/v1/stories/" + id, 
      success: refreshNewStories, 
      error: foundAllNewFailure 
     }); 
    }; 

}); // UPDATE 
+0

'.prev()'不會做你認爲它做的事情。 '.storyID'不是'.UpdateStory'之前的元素。 – Barmar

+0

使用'.prevAll()',就像在這裏的解決方案中一樣:http://stackoverflow.com/questions/19653267/finding-the-closest-previous-element-with-specific-data-attribute-jquery/19653351#19653351 – Barmar

+0

@Barmar這是有道理的,謝謝..這仍然是日誌未定義,但..任何其他建議? – StackThis

回答

1

它應該是:

var group = $(this).closest(".input-group-addon"); 
var id = group.prevAll(".storyID").val(); 
var story = group.prevAll(".currentStory").val(); 
+0

完美!非常感謝 – StackThis

+0

jquery對於一個複選框等同於什麼?如果(group.prevAll(「。archiveCheck」)。is(「:checked」)){var archiveCheck ='archived';}'似乎不工作..對於html:'' – StackThis

+0

您在複選框後有複選框。 'prevAll'只在該範圍之前查找事物。 – Barmar

相關問題