像按钮不递增计数

时间:2015-11-06 08:35:13

标签: javascript html ruby-on-rails ajax button

我想要做的是'like'按钮增加dest对象的like_count参数。但是,通过我正在进行的ajax调用,like_count参数没有递增。

这是我的javascript文件的一部分“

  Dashboard = (function() {
var trip_id;
// var apiUrl = 'https://planit-169.herokuapp.com';
var apiUrl = '';
var trip_id;
var create;
var submit;



/**
* HTTP GET request
* @param  {string}   url       URL path, e.g. "/api/smiles"
* @param  {function} onSuccess   callback method to execute upon request success (200 status)
* @param  {function} onFailure   callback method to execute upon request failure (non-200 status)
* @return {None}
*/
 var makeGetRequest = function(url, onSuccess, onFailure) {
   $.ajax({
       type: 'GET',
       url: apiUrl + url,
       dataType: "json",
       success: onSuccess,
       error: onFailure
   });
 };

 /**
 * HTTP POST request
 * @param  {string}   url       URL path, e.g. "/api/smiles"
 * @param  {Object}   data      JSON data to send in request body
 * @param  {function} onSuccess   callback method to execute upon request success (200 status)
 * @param  {function} onFailure   callback method to execute upon request failure (non-200 status)
 * @return {None}
 */
var makePostRequest = function(url, data, onSuccess, onFailure) {
    $.ajax({
        type: 'POST',
        url: apiUrl + url,
        data: JSON.stringify(data),
        contentType: "application/json",
        dataType: "json",
        success: onSuccess,
        error: onFailure
    });
};

/**
* HTTP DELETE request
* @param  {string}   url       URL path, e.g. "/api/smiles"
* @param  {function} onSuccess   callback method to execute upon request success (200 status)
* @param  {function} onFailure   callback method to execute upon request failure (non-200 status)
* @return {None}
*/
 var makeDeleteRequest = function(url, onSuccess, onFailure) {
   $.ajax({
       type: 'DELETE',
       url: apiUrl + url,
       dataType: "json",
       success: onSuccess,
       error: onFailure
   });
 };    

/** One-stop shop to update the dashboard. This will make the request to get
  * TRIP object, and pass it to the necessary call on click. Please put any
  * functions that need to be called here.
  */
 var updateDash = function(data) {
    var url = '/trips/' + trip_id;
    var onSuccess = function(data) {
        console.log("succesfully updated dash");
        updateHeader(data.trip);
        resetTable();
        initializeMap();
        insertAllDest(data.trip);

    };

    var onFailure = function() {
        console.log("something went wrong");
    }

    //if the ajax call has already been made
    if (data) {
        onSuccess(data);
    } else {
        makeGetRequest(url, onSuccess, onFailure)
    }
};

var updateHeader = function(trip) {
    console.log('updating');
    // var trip = data.trip;
    var users = trip.users;
    var user_count = Object.keys(users).length;
    console.log(trip);
    $('h1[data-header="location"]').html(trip.location);
    $('aside[data-header="invited-dates"').html("invited: " + user_count + " dates: " + trip.start_date + " - " + trip.end_date);
    $('a[data-function="invite-friends"').removeClass('hidden');
    $('a[data-function="form-save"').removeClass('hidden');
    menu_close();
}

var toggleElement = function($that, offset, toggle) {
    var height = $that.height() + offset;
    if (toggle === "down") {
        $that.animate({"top": '+=' + height}, 'slow','swing');
        $('.main-content').css('opacity', .5);
    } else {
        $that.animate({"top": '-=' + height}, 'slow','swing');
        $('.main-content').css('opacity', 1);
    }
}



/** =========================Destination Handler + Functions ============== */
var attachSubmitDestHandler = function(e) {
    submit.on('click', '.submit-input', function(e){
        e.preventDefault ();
        var name = submit.find('.name-input').val();
        var address = submit.find('.address-input').val();
        var dest = {};
        dest.name = name;
        dest.address = address;
        dest.trip_id = 1;
        dest.like_count = 0;

        var onSuccess = function(data) {
            if (!data.errors){
                console.log(data);
                insertDest(data["destination"]);
                submit.find('.name-input').val('')
                submit.find('.address-input').val('')
            }else{
                for (i in data.errors){
                    console.log(data.errors[i]);
                }
            }

        };
        var onFailure = function(data) {
            console.log("failure");

        };
        var that = this;
        url = "/api/destinations?trip_id=" + trip_id;
        console.log(url);
        makePostRequest(url, dest, onSuccess, onFailure);
    });

};

    /**
 * Insert dest into Itinerary List Table
 * @param  {Object}  dest        JSON
 * @return {None}
 */
var insertDest = function(dest) {
  // Find a <table> element with id="myTable":
  var table = document.getElementById("destTable");

  // Create an empty <tr> element and add it to the 1st position of the table:
  var row = table.insertRow(1);

  // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:

  var name_cell = row.insertCell(0);
  var address_cell = row.insertCell(1);
  // var delete_cell = row.insertCell(2);

  var like_cell = row.insertCell(2);
  like_cell.innerHTML = '<input id="target" type="button" value="Like"</input>';
  //'<button id="target" type="button">Like</button>';
  //'<span class="likebtn-wrapper" data-identifier="item_1"></span>';
  //'<input type="button" id="add1" data-index="1" class="add" value="1+" title="Add"/>';
  var like_count_cell = row.insertCell(3);
  like_count_cell.innerHTML= dest.like_count;
  //'<div id="output" value =0></div>';
  //

  $('#target').click(function() {
    dest.like_count += 1;
    return dest.like_count;
    //$('#output').html(function(i) { return dest.like_count});
})


  // Add some text to the new cells:
  name_cell.innerHTML = dest.name;
  address_cell.innerHTML = dest.address;
  // delete_cell.innerHTML = "<div class='del'>x</div>";
  addMarker(dest.address,map);
};

var insertAllDest = function(trip){
    var d = trip.destinations;
    for (i in d){
        insertDest(d[i]);
    }
};

var resetTable = function() {
    $('#destTable tr').not('.table-initial').remove();
}

//function increaseLike() {
  //  dest.like_count += 1;
//}
/*$('#target').click(function() {
    $('#output').html(function(i, val) { return val*1+1 });
});*/

/*$(document).on("click", ".likebtn-wrapper", function(d,e,s){
    if(d.getElementById("likebtn_wjs"))
        return;
    a=d.createElement(e);
    m=d.getElementsByTagName(e)[0];
    a.async=1;
    a.id="likebtn_wjs";
    a.src=s;
    m.parentNode.insertBefore(a, m)})  (document,"script","//w.likebtn.com/js/w/widget.js");
}*/
/*function generateElement(index) {
return $("<input />", {
    type: "button",
    class: "add",
    value: index + "+",
    title: "Add",
    "data-index": index
});
$(document).on("click", ".add", function(e){
var newIndex = Number($(this).attr("data-index")) + 1;
var newElem = generateElement(newIndex);
$("#container").append(newElem);
}); 
}*/



/** =======================End of destinations handlers ======================= */

/** =========================End Handlers =====================================     */


/** ==MAP== **/

var start = function() {
    create = $(".create");
    submit = $(".submit");
    submit1 = $(".search-button");
    like = $(".like-btn");

    attachMenuHandler();
    attachLocationHandler();
    attachSubmitDestHandler();
    attachFriendHandler();
    attachCreateTripHandler();
    initializeSearch();
    attachLikeHandler();
};

return {
    start: start
};
})();

1 个答案:

答案 0 :(得分:0)

你的代码没有完成。我猜目标是由代码动态添加的。当绑定点击事件时,目标不存在。

$(document).on('click','#target',function(){
     //TODO:
})