特定のボタンクラスOnClickの前にある特定のフィールドの値は未定義ですか?

StackOverflow https://stackoverflow.com//questions/24048322

質問

このようなものをテストして、繰り返し更新ボタンのクリック前のフィールドの値を取得するが、ブラウザコンソール

undefined値をログに記録しました。
var $prevID = $(this).prevAll('.UpdateStory').first(".storyID");
var $prevStory = $(this).prevAll('.UpdateStory').first(".currentStory");

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

これはHTML(クライアントサイド+サーバーサイドハンドルバーズ数)

です。
<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 .put

// 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
.

役に立ちましたか?

解決

それは次のようになるべきです:

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top