简体   繁体   English

获取所有列表项的属性并将其添加到输入中

[英]Get attribute of all list items and add them to input

I have a list like this: 我有一个这样的清单:

<ul class="draggable">
    <li data-bullet="1"> item 1</li>
    <li data-bullet="2"> item 2</li>
    <li data-bullet="3"> item 3</li>
</ul>

Using javascript, how do I grab all the list item attributes data-bullet and insert them into the value of an input (separated by a comma): 使用javascript,如何获取所有列表项属性data-bullet并将其插入到输入值(用逗号分隔)中:

<input id="insertme" type="hidden" name="bullet" value="">

So the end result will be: 因此最终结果将是:

<input id="insertme" type="hidden" name="bullet" value="1,2,3">

I know how to get individual list items but can't get my head around how to get them all and insert them there. 我知道如何获取单个列表项,但无法理解如何将它们全部插入并插入其中。

Here you go, A pure javascript solution 随您去,纯JavaScript解决方案

Try to use dataset at this context, 尝试在这种情况下使用dataset

var res = "";
[].forEach.bind(document.querySelectorAll(
   '.draggable > li[data-bullet]'),function(itm, i){
  res += ((i) ? ":" : "") + itm.dataset.bullet;
})();

document.getElementById("insertme").value = res;

DEMO 演示

Or the less complex and a readable version would be, 或不太复杂且易于阅读的版本,

var elemArray = Array.from(document.querySelectorAll('.draggable > li[data-bullet]')),
    res ="";
elemArray.forEach(function(){
 res += ((i) ? ":" : "") + itm.dataset.bullet;
});
document.getElementById("insertme").value = res;

As per your new requirement, you can accomplish your task by, 根据您的新要求,您可以通过以下方式完成任务:

$("button").click(function() {
  var parent = $(this).parent(); 
  parent.closest(".draggable").next(":text").val(parent.siblings("li").addBack().map(function(){
    return $(this).data("bullet")
  }).get().join(":"));
});

DEMO 演示

try 尝试

var allBullets = [];
$(".draggable li").each(function(){
 allBullets.push($(this).attr("data-bullet"));
});
$("#insertme").val(allBullets.join(","));

If you can use querySelectorAll to find elements and then map it using getAttribute method. 如果可以使用querySelectorAll查找元素,然后使用getAttribute方法将其映射。 For example (ES6 syntax): 例如(ES6语法):

const items = document.querySelectorAll('.draggable li');
const result = [...items].map(el => el.getAttribute('data-bullet')).join();
document.getElementById('insertme').value = result;

ES5 analogy: ES5类比:

var items = document.querySelectorAll('.draggable li');
var result = [].slice.call(items).map(function(el) {
    return el.getAttribute('data-bullet');
}).join();
document.getElementById('insertme').value = result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM