[英]How do you get every value for an attribute that all the elements contain from a selector?
this is my first question and i hope it makes sense because i am quite a rookie at javascript/jquery. 这是我的第一个问题,我希望这是有道理的,因为我是javascript / jquery的新手。
So, i have a varying amount of elements with the custom attribute data-value=<?php echo $value ?>
所以,我有不同数量的具有自定义属性
data-value=<?php echo $value ?>
的元素
Once the page has loaded I have some javascript $('[data-value]')
to select all the elements on the page with the attribute 'data-value'. 页面加载完成后,我将使用一些javascript
$('[data-value]')
选择页面上具有属性'data-value'的所有元素。 This returns an array with all the relevant elements. 这将返回一个包含所有相关元素的数组。 Then i tried getting the values with
$('[data-value]').data('value')
. 然后我尝试使用
$('[data-value]').data('value')
。 Now, while this is returning the right result, it's only returning it for the first element it comes across. 现在,虽然这将返回正确的结果,但仅针对遇到的第一个元素返回它。 I tried iterating through the code with
$('[data-value]')[num].data('value')
where 'num' is between zero and the array length. 我尝试使用
$('[data-value]')[num].data('value')
遍历代码,其中'num'在零和数组长度之间。 This, sadly, didn't work. 不幸的是,这没有用。
So is there any way to grab all the values of a particular attribute that all the selected elements have? 那么,有什么方法可以获取所有选定元素具有的特定属性的所有值?
To get the values of all the selected elements, you need to loop through the list and pick the value of those, like this: 要获取所有选定元素的值,您需要遍历列表并选择这些元素的值,如下所示:
var values = $("[data-value]").map(function(i, el) {
return el.data('value');
});
console.log(values);
Hope that helps! 希望有帮助!
you can do something like this: 您可以执行以下操作:
$('[data-value]').each(function(){
console.log($(this).data('value'));
});
You can use the .each() method to iterate through your elements. 您可以使用.each()方法迭代元素。
$('[data-value]').each(function() {
console.log( $(this).data('value');
}
You can also use the for loop as you have tried, with a simple modification. 您也可以尝试修改,然后使用for循环。 When you do
$('[data-value]')[num]
, you actually get the native element, and not a jQuery object, so .data()
is no longer available. 当您执行
$('[data-value]')[num]
,实际上得到的是本机元素,而不是jQuery对象,因此.data()
不再可用。 To fix this, you can re-wrap the element in a jQuery object. 要解决此问题,您可以将元素重新包装在jQuery对象中。
$( $('[data-value]')[num] ).data('value')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.