如何在.each()上添加一组不同的值?

时间:2018-04-07 01:22:52

标签: javascript jquery

我运行以下内容,但这不是为什么我想

HTML

<button type="button" class="removeJiku btn btn-danger">Remove</button>
<span  class="removeId" data-thisPostId="248"></span>

<button type="button" class="removeJiku btn btn-danger">Remove</button>
<span  class="removeId" data-thisPostId="242"></span>

JS

  $(".removeJiku").each(function(){
    var removeThisId = $(this).next(".removeId").attr("data-thisPostId");
    $("#usp-form-253 #usp-custom-3").attr("value", removeThisId.replace(/,/g, ", "));
  });

我需要将这些值添加为输入值,并以逗号分隔,以便:

<input type="text" id="usp-custom-3" value="242, 248">

4 个答案:

答案 0 :(得分:1)

您可以在放入输入字段之前将其存储在字符串var中,而不使用正则表达式

var strval= "";
var counter = 0;
$(".removeJiku").each(function(){
    var removeThisId = $(this).next(".removeId").attr("data-thisPostId");
     strval += (counter > 0 ? ", " : "") + removeThisId;
     counter++;
});
$("#usp-form-253 #usp-custom-3").val(strval);

答案 1 :(得分:1)

list7 = [1, 2, 3, 4, 5] list8 = [1, 2] print ([x for i,x in enumerate(list7) if x in list8]) 有两个默认变量$().eachindex

比较element是否等于(index+1)以确定是否添加逗号(索引从0开始)

$('.removeJiku').length
$(".removeJiku").each(function(index, element) {
    var removeThisId = $(this).next(".removeId").attr('data-thisPostId');
    var comma = (index+1) == $(".removeJiku").length ? "" : ", ";
    var value = $("#usp-custom-3").val() + removeThisId + comma;
    $("#usp-custom-3").val(value);
});

答案 2 :(得分:1)

您需要先获取属性值,然后添加它。但这没有正则表达式

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="removeJiku btn btn-danger">Remove</button>
<span class="removeId" data-thisPostId="248"></span>

<button type="button" class="removeJiku btn btn-danger">Remove</button>
<span class="removeId" data-thisPostId="242"></span>
<input type="text" id="usp-custom-3" value="">

答案 3 :(得分:1)

您可以使用.map().toArray().join()使其变得非常简洁。

$("#usp-custom-3").val(
  $(".removeJiku + .removeId").map((i, el) => $(el).attr("data-thisPostId"))
                              .toArray()
                              .join(", ")
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="removeJiku btn btn-danger">Remove</button>
<span class="removeId" data-thisPostId="248"></span>

<button type="button" class="removeJiku btn btn-danger">Remove</button>
<span class="removeId" data-thisPostId="242"></span>

<input type="text" id="usp-custom-3" value="">

或者没有jQuery:

document.querySelector("#usp-custom-3").value =
  [...document.querySelectorAll(".removeJiku + .removeId")]
     .map(el => el.dataset.thispostid)
     .join(", ");
<button type="button" class="removeJiku btn btn-danger">Remove</button>
<span class="removeId" data-thisPostId="248"></span>

<button type="button" class="removeJiku btn btn-danger">Remove</button>
<span class="removeId" data-thisPostId="242"></span>

<input type="text" id="usp-custom-3" value="">