簡體   English   中英

如何獲取具有某個屬性的所有元素的值

[英]How to get the value of all elements with a certain attribute

我需要獲取具有特定屬性的所有元素的值。

我有很多這樣的元素

<input data-ini="3" class="form-control" type="time">

屬性是 day_of_week_ini,我將在這樣的函數中接收一周中的某一天

function createNewPeriod(day_of_week){
    //i should have all values inside an array
}

//編輯

我需要用 jquery 做到這一點

您應該像開發人員所說的那樣在這種情況下使用數據屬性,並在現在編輯的元素中設置值屬性。 然后你可以使用下面的jQuery代碼。

var allElements = jQuery("[data-ini]");
var myArray = [];
for(var i = 0; i < allElements.length; i++) {
    myArray.push(allElements[i].val());
}

 /*input[data-ini] is the css selector. second parameter of jQuery map function is DOM element, so we retrieved the attr value using jquery. $(element) convert the DOM element to jQuery object.*/ var a = $('input[data-ini]').map((index,element)=> $(element).attr('data-ini')); console.log(a);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <!-- A series of html time controls with data attribute data-ini --> <input data-ini="3" class="form-control" type="time" value="18:00"> <input data-ini="4" class="form-control" type="time" value="16:00"> <input data-ini="5" class="form-control" type="time" value="02:00"> <input data-ini="6" class="form-control" type="time" value="03:00"> </body>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM