简体   繁体   中英

Change multiple HTML element from ajax success

I have an ajax on success function where I wrote some css color changing task upon satisfying some conditions.I'm changing the html element's color using "document.getElementById" . My problem is that there should me more than one data object where html element should be change but in that case its always the last object.

My on success function:

            success: function (data) {
            $.each(data, function (index, value) {
                if (userId == value.ApplicationUserId && postId == value.PostId && value.IsLiked == 1) {
                    document.getElementById(likeId).style.color = "red";
                }
                if (userId == value.ApplicationUserId && postId == value.PostId && value.IsLiked == 2) {
                    document.getElementById(dislikeId).style.color = "red";
                }
                if (userId == value.ApplicationUserId && postId == value.PostId && value.IsHelpfull == 1) {
                    document.getElementById(helpfulId).style.color = "red";
                }
            });
        }

And my element ID's are all unique and dynamically generated.Also I'm passing the right Id inside documet.getElementById. How can I change all elements satisfying the conditions ?

Given your clarification in the comments it seems you want something like this.

First, since the first two conditions of all of your conditionals are the same, you can check those once and nest the other checks within it.

if (userId == value.ApplicationUserId && postId == value.PostId) {
    ...
}

Then, you have two separate cases to check:

  1. If it's liked or disliked. Since these are mutually exclusive you can combine them with an else .
if (value.IsLiked == 1) {
    document.getElementById(likeId).style.color = "green"; // Liked color
} else if (value.IsLiked == 2) {
    document.getElementById(dislikeId).style.color = "red"; // Disliked color
}
  1. If it's helpful
if (value.IsHelpfull == 1) {
  document.getElementById(helpfulId).style.color = "blue"; // Helpful color
}

success: function (data) {
  $.each(data, function (index, value) {
    if (userId == value.ApplicationUserId && postId == value.PostId) {

      if (value.IsLiked == 1) {
        document.getElementById(likeId).style.color = "green";
      } else if (value.IsLiked == 2) {
        document.getElementById(dislikeId).style.color = "red";
      }

      if (value.IsHelpfull == 1) {
        document.getElementById(helpfulId).style.color = "blue";
      }

    }
  });
}

ps: check that your spelling of helpful is consistent and correct throughout.

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