JQuery - 如何用 .each 连接文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14850695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:59:50  来源:igfitidea点击:

JQuery - How to concatenate text with .each?

jqueryconcatenation

提问by skytorner

First of all, excuse me for my bad english.

首先,请原谅我的英语不好。

I've tried various methods but haven't had any luck as of yet.

我尝试了各种方法,但到目前为止还没有任何运气。

I'm returning a series of objects with .each()method.

我正在使用 .each() 方法返回一系列对象。

I'd like to populate the "value" attribute of a input field with each value from the object. I didnt find a way to do the same thing as PHP .=

我想用对象中的每个值填充输入字段的“值”属性。我没有找到与 PHP 相同的方法。=

Any idea would be great!

任何想法都会很棒!

Here's my code :

这是我的代码:

$.each($("input[type='checkbox']:checked"), function(){
        var data = $(this).parent().parent().find("td:eq(1)"); 
         $("#login").val(data.text());
    })

回答by Adil

You can use map(). You can pass the delimitercharacter to join()to separate the alues.

您可以使用map()。您可以将delimiter字符传递给join()以分隔 alues。

text = $("input[type='checkbox']:checked").map( function(){
    return $(this).parent().parent().find("td:eq(1)");        
}).get().join();

$("#login").val(text);

回答by Denys Séguret

var c = '';
$.each($("input[type='checkbox']:checked"), function(){
    var data = $(this).parent().parent().find("td:eq(1)"); 
    c += data.text();
})
$("#login").val(c);

You could also have used this in the loop :

您也可以在循环中使用它:

$("#login").val($("#login").val(c)+data.text());

but I personally prefer to minimize the changes of the DOM.

但我个人更喜欢尽量减少 DOM 的变化。

Note also that using traversals like parent().parent()lead to maintenance problems. In your case you could probably use

还要注意,使用像遍历这样的方法parent().parent()会导致维护问题。在你的情况下,你可能会使用

var data = $(this).closest('tr').find("td:eq(1)"); 

so that the code won't break if a spanor any other elements wraps your input in the future.

以便将来在 aspan或任何其他元素包装您的输入时代码不会中断。