Select all same class elements and store in string

2020-06-18 16:45发布

问题:

I Have a page which has comments left by users, each post has has its own id which is stored in a hidden input tag, in order to dynamically get the latest posts I need to know the id's of all posts and place them in a string, each id needs to be separated by a comma.

for example...

HTML markup

<div class='msgPost'><div class='msgContainer'>
    <input class='activityId' type='hidden' value='579'>
    <span>
        <div class='name'>Bob</div>nm
    </span>
</div>

<div class='msgPost'><div class='msgContainer'>
    <input class='activityId' type='hidden' value='578'>
    <span>
        <div class='name'>Tom</div>4
    </span>
</div>

<div class='msgPost'><div class='msgContainer'>
    <input class='activityId' type='hidden' value='577'>
    <span>
        <div class='name'>John</div>123
    </span>
</div>

Jquery code

function getLatestActivities(){
   var ignoreMessagesColl = $("input.activityId").val();

   $.ajax({
      traditional: true,
      dataType: "json",
      type: "GET", url: "include/process.php", 

      data:{
         getLatestActivity: "true",
         toUser: "4",
         ignoreMessages: ignoreMessagesColl
      },

      success: function(data){
         $.each(data, function (i, elem) {
            $('.commentMessage').after(elem.value);
         });              
      }
   });   
}

at the moment the variable ignoreMessagesColl only finds the first class instance of .activityid which has the value "579", but i actually need ignoreMessageColl to have the value "579, 578, 577"

回答1:

val only returns the first one's value, try map plus get plus join:

var ignoreMessagesColl = $("input.activityId").map(function() {
        return this.value;
    }).get().join(",");

What that does:

  1. map loops through all of the matched elements and builds a jQuery-wrapped array of whatever the iterator function returns.

  2. get gets the underlying array from the jQuery wrapper (I have no idea why map returns a jQuery wrapper).

  3. join combines the elements of the array into a string delimited with the given delimiter.

The end result for your example data is that ignoreMessagesColl will have "579,578,577".



回答2:

var values = [];    

$('.msgContainer input.activityId').each(function(){

    values.push($(this).val());
});

console.log(values);


回答3:

You should have:

var arr = [], str;
$("input.activityId").each(function(){
   arr.push(this.value);
});
str = arr.join(',');


回答4:

var ignoreMessagesCol = $("input.activityId").map(function() {
   return $(this).val();
}).get().join(", ");

.map() will execute the inner anonymous function for every element in the selector and return a jQuery object collection. .get() will make it an array. .join() will make it a comma separated string



标签: jquery html ajax