选择所有同一类的元素,并存储在弦元素

2023-09-10 16:33:19 作者:回忆如烟丶烟如梦

我有一个网页,其中有用户留下评论,每个岗位已经有自己的ID,它是保存在一个隐藏的输入标签,以动态获取我需要知道该ID的所有帖子,并把他们最新的帖子在字符串中,每个ID必须用逗号分隔。

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.

例如...

HTML标记

<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);
         });              
      }
   });   
}

此刻的变量 ignoreMessagesColl 只能找到.activityid的第一个类的实例其值为579,但我真的需要ignoreMessageColl有值579,578,577

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"

推荐答案

VAL 只返回第一个人的价值,尽量地图加上 GET 加上加入

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(",");

什么一样:

地图 遍历所有匹配的元素和无论构建迭代函数返回一个jQuery包裹的阵列。

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

GET 从jQuery包装得到基本数组(我不知道为什么地图返回一个jQuery包装)。

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

加入 结合的元素该阵列为分隔给定的分隔符的字符串。

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

为您的示例数据的最终结果是, ignoreMessagesColl 579578577

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

 
精彩推荐