从<img tag=""

时间:2017-12-15 15:58:17

标签: jquery

="" 上的自定义属性中获取数据请检查代码底部的javascript代码。我的目标是将所有data-cc属性值作为数组存储到名为“collection”的变量中。我已经做了下面的代码,但是我缺少的东西根本不起作用。提前致谢

<!DOCTYPE html>
<html>
<head>
    <title>test</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">


</head>
<body>

<p id="fl">
  <img src="/images/flags/il.svg" data-cc="a" class="zastavica" />
  <img src="/images/flags/il.svg" data-cc="b" class="zastavica" />
  <img src="/images/flags/il.svg" data-cc="c" class="zastavica" />
</p>


<script>
  var collection = $(this).attr('data-cc');
  console.log(collection);
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

使用.each()循环抛出图像并将值添加到数组

请参阅代码段

&#13;
&#13;
var collection = [];
$('[data-cc]').each(function() {
  collection.push($(this).attr('data-cc'));
});

console.log(collection);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="fl">
  <img src="/images/flags/il.svg" data-cc="a" class="zastavica" />
  <img src="/images/flags/il.svg" data-cc="b" class="zastavica" />
  <img src="/images/flags/il.svg" data-cc="c" class="zastavica" />
</p>
&#13;
&#13;
&#13;