簡體   English   中英

獲取所有列表項的屬性並將其添加到輸入中

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

我有一個這樣的清單:

<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>

使用javascript,如何獲取所有列表項屬性data-bullet並將其插入到輸入值(用逗號分隔)中:

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

因此最終結果將是:

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

我知道如何獲取單個列表項,但無法理解如何將它們全部插入並插入其中。

隨您去,純JavaScript解決方案

嘗試在這種情況下使用dataset

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

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

演示

或不太復雜且易於閱讀的版本,

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

根據您的新要求,您可以通過以下方式完成任務:

$("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(":"));
});

演示

嘗試

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

如果可以使用querySelectorAll查找元素,然后使用getAttribute方法將其映射。 例如(ES6語法):

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

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