Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获取页面上特定数据属性的所有值并使用收集的值_Javascript_Jquery_Html - Fatal编程技术网

Javascript 如何获取页面上特定数据属性的所有值并使用收集的值

Javascript 如何获取页面上特定数据属性的所有值并使用收集的值,javascript,jquery,html,Javascript,Jquery,Html,我有一个具有数据属性的元素列表,如下所示: <div class="first-div" data-month="march"></div> <div class="first-div" data-month="june"></div> 然而,这是行不通的。似乎无法使用月份元素。有人知道怎么做吗 它在所有浏览器中都能工作吗?您的month变量将是一个jquery对象。您需要提取月份的字符串值 但据我所知,这似乎没有必要。您只需将事件侦听器直接分配

我有一个具有数据属性的元素列表,如下所示:

<div class="first-div" data-month="march"></div>
<div class="first-div" data-month="june"></div>
然而,这是行不通的。似乎无法使用月份元素。有人知道怎么做吗


它在所有浏览器中都能工作吗?

您的
month
变量将是一个jquery对象。您需要提取月份的字符串值

但据我所知,这似乎没有必要。您只需将事件侦听器直接分配给
每个

试着做:

$('[data-month]').each(function(i, monthEl) {
    $(monthEl).bind('click', function() {
        // If you need to get the month value, you can use jQuery's .data()
        var monthString = $(monthEl).data('month');
    });
});

您应该将
.forEach
更改为
。每个
和月份参数都是
div
元素,而不是字符串

$('[data-month]').each(function(month) {
    $('[data-month="' + month.getAttribute('data-month') + '"]').bind('click', function() {
        alert(month);
    });
});

谢谢是否有更干净的方法提取月值?我多次使用它并找到
$('[data month]')。forEach(函数(e){var month=e.data('month');
(带有额外的赋值)有点长。我必须问你为什么要这样做。在你的
forEach
中,你已经在迭代元素了。为什么你必须在循环中再次找到元素?我必须调用一个使用该值的url。顺便说一下,代码不起作用。仍然没有单击事件。:/forEach调用不起作用(控件只是跳过它)。返回
TypeError:$(…)。forEach实际上不是一个函数
Ah。请重新编辑
$('[data-month]').each(function(month) {
    $('[data-month="' + month.getAttribute('data-month') + '"]').bind('click', function() {
        alert(month);
    });
});