简体   繁体   English

计算并定义具有特定 ID 前缀的输入数量

[英]Count and define number of inputs with specific ID prefix

I have a table with 33 inputs with ID's ranging from 1 - 33. So for example they range from "price-1" all the way to "price-33"我有一个包含 33 个输入的表,ID 的范围为 1 - 33。例如,它们的范围从“price-1”一直到“price-33”

Instead of individually define these elements one by one like this:而不是像这样一个一个地单独定义这些元素:

var p1 = document.getElementById("price-1");
var p2 = document.getElementById("price-2");

How can I automatically count (perhaps count by the price- prefix?) and define each of these elements using JavaScript (or jQuery if it's easier)?我怎样才能自动计数(也许通过price-前缀计数?)并使用 JavaScript(或 jQuery,如果更简单的话)定义每个元素?

You can try using Attribute selectors ( starts with:- [attr^=value] ):您可以尝试使用属性选择器(以:- [attr^=value]开头):

Represents elements with an attribute name of attr whose value is prefixed (preceded) by value.表示属性名称为 attr 的元素,其值以值作为前缀(前置)。

Demo: Using vanilla JS:演示:使用 vanilla JS:

 var elList = document.querySelectorAll('[id^=price-]'); console.log(elList.length); //5 //loop throgh all the elements whose id starts with price- var data = {}; elList.forEach(function(el){ data[el.id] = el.value; }); console.log(data);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="price-1" value="100"/> <input id="price-2" value="200"/> <input id="price-3" value="300"/> <input id="price-4" value="400"/> <input id="price-5" value="500"/>

OR: Using jQuery或:使用 jQuery

 var count = $('[id^=price-]').length; console.log(count); //5 //loop throgh all the elements whose id starts with price- var data = {}; $('[id^=price-]').each(function(){ data[this.id] = this.value; }); console.log(data);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="price-1" value="100"/> <input id="price-2" value="200"/> <input id="price-3" value="300"/> <input id="price-4" value="400"/> <input id="price-5" value="500"/>

You can use querySelectorAll for this purpose:为此,您可以使用querySelectorAll

 // Get all elements where id starts with `price` text const prices = document.querySelectorAll('*[id^="price"]'); // Loop through each one of them [...prices].forEach(price => { console.log('id: ', price.id); console.log('value: ', price.value); });
 <input type="text" id="price-1" value="10" /> <input type="text" id="price-2" value="20"/>

尝试这个:

document.querySelectorAll('[id^="price-"]').forEach((el, i) => console.log(el, i))

The motivation why I would prefer to use a data field is because I consider id to be a unique identifier related to the DOM element.我更喜欢使用data字段的动机是因为我认为id是与 DOM 元素相关的唯一标识符。

Your example doesn't suggest price being a unique identifier, but rather a workaround to allow crawling the DOM for price element.您的示例并不建议 price 是唯一标识符,而是一种允许为 price 元素抓取 DOM 的解决方法。
Even when it would concern a unique identifier, let's say an id as primary key from a database, I would use something like data-id , as this more descriptively mentions that we are talking about the actual data rather than a DOM element's id that may or may not be just a generic description that merely focuses on uniqueness.即使它涉及唯一标识符,假设 id 作为数据库中的主键,我也会使用类似data-id东西,因为这更具描述性地提到我们正在谈论实际数据而不是 DOM 元素的 id 可能或者可能不仅仅是只关注独特性的通用描述。

Because of this, it makes more sense to have a generic attribute to identify the price (this anything you want it to be semantically), and you can allocate custom data field that you want to retrieve later in your javascript code.因此,使用通用属性来标识价格(这是您希望它在语义上的任何内容)更有意义,并且您可以分配稍后要在您的 javascript 代码中检索的自定义数据字段。

Without being fancy:不花哨:

<div>
    <div data-type="price" data-price='5'>5<span>$</span></div>
    <div data-type="price" data-price='6'>6<span>$</span></div>
</div>

var prices = document.querySelectorAll("[data-type='price']");

for (let i = 0; i < prices.length; i++) {
    console.log('price:', prices[i].getAttribute('data-price'));
}

https://jsfiddle.net/b03c7ars/ https://jsfiddle.net/b03c7ars/

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

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