jquery每个函数 - >类名是"未定义" for $(" .row> div")。each(function(i){};

时间:2017-06-25 21:21:15

标签: jquery variables undefined each

我收到了一个" myval:undefined"以下代码的消息。 我想知道如何获得当前班级的课程内容?

这是我的功能:

$(".row > div").each(function(i) {
            var myval = $(this).attr('class');
             console.log ("myval: " + myval)
});

HTML:

<div class="row">
 <div class="item1">item</div>
 <div class="item2">item</div>
</div>

<div class="row">
 <div class="item3">item</div>
 <div class="item4">item</div>
</div>

<div class="row">
 <div class="item5">item</div>
 <div class="item6">item</div>
</div>

etc.

2 个答案:

答案 0 :(得分:1)

我看不到您的代码有任何问题,请检查您是否正确包含了jQuery库。

此处示例: http://jsbin.com/rutameg/edit?html,js,console,output

$(".row > div").each( function() { // Removed i as not in use
            var myval = $(this).attr('class');
             console.log ("myval: " + myval)
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  
  
  
  <div class="row">
 <div class="item1">item 1</div>
 <div class="item2">item 2</div>
</div>

<div class="row">
 <div class="item3">item 3</div>
 <div class="item4">item 4</div>
</div>

<div class="row">
 <div class="item5">item 5</div>
 <div class="item6">item 6</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</div>

</body>
</html>

答案 1 :(得分:1)

您的代码是正确的,结果是预期的

&#13;
&#13;
$(".row > div").each( function(i) { // Removed i as not in use
            var myval = $(this).attr('class');
             console.log ("myval: " + myval)
});
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  
  
  
  <div class="row">
 <div class="item1">item 1</div>
 <div class="item2">item 2</div>
</div>

<div class="row">
 <div class="item3">item 3</div>
 <div class="item4">item 4</div>
</div>

<div class="row">
 <div class="item5">item 5</div>
 <div class="item6">item 6</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</div>

</body>
</html>
&#13;
&#13;
&#13;