简体   繁体   中英

Javascript jquery access global variables inside an event listner 'this' is not used

I am a beginner. I was trying to access an object inside the jquery event listner but get either undefined or typerror. I tried a few ways tried sending object this way {results: result} but it didn't work, gave me undefined error. I could not find an answer that works in my case. Thanks in advance

Jquery entire code

$(document).ready(function() {
//var $addhere = $("#addhere");
$.ajax({
    type: "GET",
    url: "/newsfeed/retrieve",
    //datatype: "JSON",
    success: function(datas){
        //console.log(data);
        // Check the length of success data.data
        const data = datas;
        var datalength = Object.keys(data.data).length;
        // Calling the result function
        var count = 0;
        result(data, datalength);
        reactions(data, datalength, count);

    }
});

function result(result, datalength){
    // Values are here im result
    console.log(result);
    var myPostHtml = '';
    // Values in the first place of object array
    //console.log(result.data[0].uploads);
    for(i=0;i<datalength;i++)
    {
      //if(result.data[i].uploads.attr("src", "No files uploaded")){
        //$("img").hide();
      //}
        myPostHtml += `<img src="${result.data[i].uploads}" id="contentAreaHomePageTweetPhoto" alt="post-image" class="img-responsive post-image" />
        <div class="post-container">
          <img src="${result.data[i].uploads}" id="" alt="user" class="profile-photo-md pull-left" />
          <div class="post-detail">
            <div class="user-info">
              <h5><a href="/timeline" id="" class="profile-link">${result.data[i].username}</a> <!--<span class="following">following</span>--></h5>
              <p class="text-muted"id="contentAreaHomePageTime">${result.data[i].createdAt}</p>
            </div>
            <div class="reaction">
              <button class="btn text-green" id="contentAreaHomePageLikeButton${result.data[i]._id}"><i class="icon ion-thumbsup"></i>0</button>
              <button class="btn text-red" id="contentAreaHomePageUpdateButton${result.data[i]._id}"><i class="fa fa-pencil-square-o"></i></button>
              <button class="btn text-red" id="contentAreaHomePageDeleteButton${result.data[i]._id}"><i class="icon ion-android-delete"></i></button>
            </div>
            <div class="line-divider"></div>
            <div class="post-text">
              <p><i class="em em-anguished"></i> <i class="em em-anguished"></i> <i class="em em-anguished"></i></p>
            </div>
            <!--<div class="line-divider"></div>-->
            <div class="">
              <!--<img src="images/users/user-11.jpg" alt="" class="profile-photo-sm" />-->
              <p id="contentAreaHomePagePostText"><b><!--<a href="/timeline" class="profile-link"></a><i class="em em-laughing"></i>-->${result.data[i].post}</b></p>

            <!--</div>
            <div class="post-comment">
              <img src="images/users/user-4.jpg" alt="" class="profile-photo-sm" />
              <p><a href="/timeline" class="profile-link">John</a> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud </h5>
            </div>
            <div class="post-comment">
              <img src="images/users/user-1.jpg" alt="" class="profile-photo-sm" />
              <input type="text" class="form-control" placeholder="Post a comment">
            </div>-->
          </div>
        </div>
        </div>
        <div class="line-divider"></div>`

    };

    $(".post-content").append(myPostHtml);
};

function reactions(result, datalength, count){ 
  console.log("Entered inside", result, datalength);

for(i=0;i<datalength;i++){
    $('#contentAreaHomePageLikeButton'+result.data[i]._id).on('click', {results: result}, function(event){
      console.log("I am button",$(this), event.data.results.data[i]);
      var like = {
        id: event.data.results.data[i]._id
      }
      console.log("This is the like",like);
      //passdata = result.data.[i]_id;
      //$(this).html(count);
      $.ajax({
        url: "/newsfeed/update",
        type: "POST",
        datatype: "JSON",
        data: {id: result.data[i]._id},
        success: function(data){
          $("#contentAreaHomePageLikeButton"+result.data[i]._id).html(count++);

        }
       });
    })
    $('#contentAreaHomePageUpdateButton'+result.data[i]._id).on('click', function(){
      console.log("I am Button");
      //$(this).html("Mayank");
      $.ajax({
        url: "/newsfeed/update",
        type: "POST",
        datatype: "JSON",
        data: {id: result.data[i]._id},
        success: function(data){
          $("#contentAreaHomePageUpdateButton"+result.data[i]._id).html(count++);

        }
       });
    })
    $('#contentAreaHomePageDeleteButton'+result.data[i]._id).on('click', function(){
      console.log("I am Button");
      console.log("I am Button", result.data[i]._id);
      //$(this).html("Mayank");
      $.ajax({
        url: "/newsfeed/delete",
        type: "POST",
        datatype: "JSON",
        data: {id: result.data[i]._id},
        success: function(data){
          $("#contentAreaHomePageDeleteButton"+result.data[i]._id).hide();

        }
      });
    })

Problem is here in code

for(i=0;i<datalength;i++){
    $('#contentAreaHomePageLikeButton'+result.data[i]._id).on('click', {results: result}, function(event){
      console.log("I am button", event.data.results.data[i]); // This gives undefined
      var like = {
        id: event.data.results.data[i]._id
      }
      console.log("This is the like",like); // This gives typeerror exact error added at end
      //passdata = result.data.[i]_id;
      //$(this).html(count);
      $.ajax({
        url: "/newsfeed/update",
        type: "POST",
        datatype: "JSON",
        data: {id: result.data[i]._id},
        success: function(data){
          $("#contentAreaHomePageLikeButton"+result.data[i]._id).html(count++);

        }
       });
    })

homepageJquery.js:84 Uncaught TypeError: Cannot read property '_id' of undefined at HTMLButtonElement. (homepageJquery.js:84)

I'd say that you might be being tripped-up by "closures." Here you have an outer loop which is issuing asynchronous JavaScript requests. Magically, the then-present value for i is available to them. But there's no guarantee that the data[] array actually contains that element when the statement is actually executed.

I see various other typographic-error problems here... result vs. results and so on. Very carefully desk-check your logic and be certain that you fully understand what it is supposed to be doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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