获取 $('div').each() 中的最后一项

发布于 2024-09-28 14:30:40 字数 1028 浏览 5 评论 0原文

我正在使用 jquery 和 every 函数,但我无法找到 ul 列表中的最后一项。

数据:

<ul id="1">
     <li>1</li>
     <li>2</li>
     <li>3</li>
</ul>
<ul id="2">
     <li>1</li>
     <li>2</li>
     <li>3</li>
</ul>
<ul id="3">
     <li>1</li>
     <li>2</li>
     <li>3</li>
</ul>

我尝试了多种方法,但没有一种方法能达到我想要的效果。这是我尝试过的。

var test = '{';
for (i = 1; i <= 3; i++) {
     test += i+':{';
     $('#'+i+' li').each(function(index,e){
          test += $(this).attr('id');

          // THIS IS THE PROBLEM AREA START
          if(index != $('#'+i).last()){
               test += ',';
          }
          // PROBLEM AREA END

     });
     test += '}';
     if(i != 3){
          test += ',';
     }
}
test += '}';
alert(test);

我也尝试过使用“$('#'+i+':last')”,但这并没有起到作用。

我想要得到的输出是:

{1:{1,2,3},2:{1,2,3},3:{1,2,3}}

I am using jquery and the each function but I am having trouble finding the last item in a ul list.

DATA:

<ul id="1">
     <li>1</li>
     <li>2</li>
     <li>3</li>
</ul>
<ul id="2">
     <li>1</li>
     <li>2</li>
     <li>3</li>
</ul>
<ul id="3">
     <li>1</li>
     <li>2</li>
     <li>3</li>
</ul>

I have tried multiple things but nothing is doing what I want. Here is I have tried.

var test = '{';
for (i = 1; i <= 3; i++) {
     test += i+':{';
     $('#'+i+' li').each(function(index,e){
          test += $(this).attr('id');

          // THIS IS THE PROBLEM AREA START
          if(index != $('#'+i).last()){
               test += ',';
          }
          // PROBLEM AREA END

     });
     test += '}';
     if(i != 3){
          test += ',';
     }
}
test += '}';
alert(test);

I have also tried using the "$('#'+i+':last')" but that did not do it ether.

The output I am trying to get is:

{1:{1,2,3},2:{1,2,3},3:{1,2,3}}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

一抹淡然 2024-10-05 14:30:40

您正在尝试从匹配的集合中选择最后一个元素(该元素仅由您的 ul 组成,而不是其子元素(即 li 元素))。您需要对当前选择的执行此操作:

$('#'+i).children('li').last()

或(作为选择器):

$('#'+i+' > li:last')

You are trying to select the last element out of the matched set (which only consists out of your ul rather than its children (which are li elements)). You need to do this on the children of the current selection:

$('#'+i).children('li').last()

or (as selector):

$('#'+i+' > li:last')
笑梦风尘 2024-10-05 14:30:40

2 项更改

  1. 使用

    测试 += $(this).text();

    而不是

    test += $(this).attr('id');

  2. 将 if 条件更改为

if($(this).next().length){

修改后的代码

var test = '{';
for (i = 1; i <= 3; i++) {
     test += i+':{';
     $('#'+i+' li').each(function(index,e){
          // Change #1
          test += $(this).text();

          // Change #2
          if($(this).next().length){
               test += ',';
          }
     });
     test += '}';
     if(i != 3){
          test += ',';
     }
}
test += '}';
alert(test);

2 Changes

  1. Use

    test += $(this).text();

    instead of

    test += $(this).attr('id');

  2. Change if condition to

if($(this).next().length){

Modified code

var test = '{';
for (i = 1; i <= 3; i++) {
     test += i+':{';
     $('#'+i+' li').each(function(index,e){
          // Change #1
          test += $(this).text();

          // Change #2
          if($(this).next().length){
               test += ',';
          }
     });
     test += '}';
     if(i != 3){
          test += ',';
     }
}
test += '}';
alert(test);
垂暮老矣 2024-10-05 14:30:40

首先,您的输出看起来像 JSON 代码。由于您已经在使用 jQuery,因此有比从头开始构建字符串更简单的方法来生成 JSON 代码。

其次,建议:如果您为

    标记使用类名,则无需为这些数字 ID 使用 for() 循环(你真的需要数字 ID 吗?它们最终会咬你的!--请记住,ID 在整个页面中应该是唯一的。另外,JSON 期望具有数字索引的数组用方括号而不是大括号表示使用)。

<ul class='mylist'>
    <li>1</li>
    ...

然后你可以编写这样的代码:

myarray=[];
$('.mylist').each(function(ulindex) {
  myarray[ulindex]=[];
  $(this).children().each(function(liindex) {
    myarray[ulindex][liindex]=$(this).text();
  })
});
$output=$.toJSON(myarray);

上面的代码未经测试,但应该足够接近,可以给你一个想法。 (注意:你可能需要一个jquery插件来获取toJSON()方法;我不记得了)

Firstly, you're output looks like JSON code. Since you're using jQuery already, there are much easier ways to generate JSON code than building the string from scratch.

Secondly, a suggestion: If you use a classname for your <ul> tags, you won't need to mess around with a for() loop for those numeric IDs (do you really need numeric IDs? They'll bite you eventually! -- Bear in mind that IDs should be unique across the page. Plus JSON expects arrays with numeric indices to be denoted with square brackets rather than the curly braces you're using).

<ul class='mylist'>
    <li>1</li>
    ...

Then you can write code like this:

myarray=[];
$('.mylist').each(function(ulindex) {
  myarray[ulindex]=[];
  $(this).children().each(function(liindex) {
    myarray[ulindex][liindex]=$(this).text();
  })
});
$output=$.toJSON(myarray);

Code above not tested, but should be close enough to give you an idea. (note: you may need a jquery plug-in to get the toJSON() method; I can't remember)

血之狂魔 2024-10-05 14:30:40

重新阅读您的问题后,您真正想要的是一种巧妙的方式来生成输出,而不是检测最后一个元素是什么。

你应该这样做:(

var rootArr = new Array();

for (i = 1; i <= 3; i++) {  
   var liArr = new Array();
   $("#" + i + " li").each(function() {
      // add code to 
      liArr.push($(this).text());
   }
   rootArr.push(i + ":{" + liArr.join(",")  + "}");
}

var result = "{" + rootArr.join(",") + "}";

基于 SkillDrick 的建议)

After re-reading your question, what you really want is a clever way to make the output, not detecting what is the last element.

You should do something like:

var rootArr = new Array();

for (i = 1; i <= 3; i++) {  
   var liArr = new Array();
   $("#" + i + " li").each(function() {
      // add code to 
      liArr.push($(this).text());
   }
   rootArr.push(i + ":{" + liArr.join(",")  + "}");
}

var result = "{" + rootArr.join(",") + "}";

(Based on SkillDrick's advice)

带刺的爱情 2024-10-05 14:30:40

我建议您使用字符串创建一个数组,然后用逗号将它们连接起来。

所以,像这样:

var arr = ["1:{1,2,3}", "2:{1,2,3}", "3:{1,2,3}"];

var str = "{" + myArray.join(",") + "}";

因此,在 each 循环的每次迭代中,您将构造一个类似 "1:{1,2,3}"的字符串将其推送到您的数组中。

I would recommend you create an array with your strings, then join them with a comma.

So something like this:

var arr = ["1:{1,2,3}", "2:{1,2,3}", "3:{1,2,3}"];

var str = "{" + myArray.join(",") + "}";

So, in each iteration of the each loop you'd construct a string like "1:{1,2,3}" and push it to your array.

与往事干杯 2024-10-05 14:30:40

jQuery 实际上利用了每个对象的 .length 属性 (http://api.jquery.com/length/)。因此,当您使用选择器并且有一个匹配元素列表时,.length - 1 将是最后一个元素的索引。
即:

var test = '{';
for (i = 1; i <= 3; i++) {
     test += i+':{';
     $('#'+i+' li').each(function(index,e){
          test += $(this).attr('id'); //This is erroneous; this (ie e)'s
                                      //id is nonexistent. Do you mean .html()?

          // THIS IS THE PROBLEM AREA START
          if(index != $('#'+i+' li').length - 1){
               test += ',';
          }
          // PROBLEM AREA END

     });
     test += '}';
     if(i != 3){
          test += ',';
     }
}
test += '}';
alert(test);

虽然这里存在不少问题。如果您将 class='include' 添加到每个

    ...

var str;
$('.include').each(function (index, e) {
    str += e.attr('id') + ": {";
    e.children().each(function (cIndex, child) {
        str += child.html() + ( cIndex != e.children().length - 1 ) ? ', ' : '';
    });
    str += '}' + ( index != e.parent().children().length - 1);
});

可能会提供一些有用的见解。基本上你想要写的是一个 JSON 序列化器。您可能想查看 http://flexjson.sourceforge.net/

jQuery actually utilizes the .length property (http://api.jquery.com/length/) of each object. So, when you are using a selector, and you have a list of matched elements, .length - 1 will be the index of the last element.
i.e.:

var test = '{';
for (i = 1; i <= 3; i++) {
     test += i+':{';
     $('#'+i+' li').each(function(index,e){
          test += $(this).attr('id'); //This is erroneous; this (ie e)'s
                                      //id is nonexistent. Do you mean .html()?

          // THIS IS THE PROBLEM AREA START
          if(index != $('#'+i+' li').length - 1){
               test += ',';
          }
          // PROBLEM AREA END

     });
     test += '}';
     if(i != 3){
          test += ',';
     }
}
test += '}';
alert(test);

Although there are more than a few problems here. If you added the class='include' to each <ul>...

var str;
$('.include').each(function (index, e) {
    str += e.attr('id') + ": {";
    e.children().each(function (cIndex, child) {
        str += child.html() + ( cIndex != e.children().length - 1 ) ? ', ' : '';
    });
    str += '}' + ( index != e.parent().children().length - 1);
});

May provide some helpful insights. Basically what you are are trying to write is a JSON serializer. You might want to check out http://flexjson.sourceforge.net/

鸢与 2024-10-05 14:30:40

问题之一是您尝试使用数字作为对象中的成员名称。我将通过在基础对象中添加“id-”前缀并在对象中使用数组来消除此问题。

    var out = {};    
    $("ul").each(function() {
        var ul = [];
        $(this).find("li").each(function() {
            ul.push($(this).text()); // maybe .html() ?
        });
        out."id-" + $(this).attr("id") = ul;
    });
    console.log(JSON.parse(out));

我还没有测试过这个,但你明白了。对每个 UL 进行排序,并对每个 UL 的每个 LI 进行排序。

应该输出:

{"id-1": [1,2,3], "id-2":, [1,2,3], "id-3":[1,2,3]}

One of the problems is you are trying to use numbers for member names in Objects. I will eleminate this by prefixing these in the base object with "id-", and using arrays within the object.

    var out = {};    
    $("ul").each(function() {
        var ul = [];
        $(this).find("li").each(function() {
            ul.push($(this).text()); // maybe .html() ?
        });
        out."id-" + $(this).attr("id") = ul;
    });
    console.log(JSON.parse(out));

I haven't tested this, but you get the idea. Sort through each UL, and sort through each LI of each UL.

Should output:

{"id-1": [1,2,3], "id-2":, [1,2,3], "id-3":[1,2,3]}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文