在jquery中将变量作为类名传递

时间:2017-06-06 10:23:35

标签: jquery html

我有班级名称' views-row5'在变量' classN'。我想将其传递给jquery以查找类名' views-row5'使用变量' classN'并添加课程' hello'。



jQuery(document).ready(function($) {
var classN="views-row5"
$('.carousel-inner li').each(function()
  {$(this).find(classN).addClass('hello');});
 }); 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-inner">
  <li>
     <div class="views-row4">1</div>
     <div class="views-row5">2</div>
  </li>
  <li>
     <div class="views-row4">1</div>
     <div class="views-row5">2</div>
  </li>
</div>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:3)

jQuery(document).ready(function($) {
  var classN = "views-row5"
  $('.carousel-inner li').each(function() {
    $(this).find("."+classN).addClass('hello');
  });
});
.hello {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-inner">
  <li>
    <div class="views-row4">1</div>
    <div class="views-row5">2</div>
  </li>
  <li>
    <div class="views-row4">1</div>
    <div class="views-row5">2</div>
  </li>
</div>

  1. 添加.以查找您要查找的课程

答案 1 :(得分:3)

你忘了.代表选择器中的类

jQuery(document).ready(function($) {
var classN="views-row5"
$('.carousel-inner li').each(function()
  {$(this).find('.'+classN).addClass('hello');});
 });
.hello{
color:green;
font-size:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-inner">
  <li>
     <div class="views-row4">1</div>
     <div class="views-row5">2</div>
  </li>
  <li>
     <div class="views-row4">1</div>
     <div class="views-row5">2</div>
  </li>
</div>

答案 2 :(得分:2)

在变量赋值中,您必须为该类添加点。比如var classN=".views-row5"

jQuery(document).ready(function($) {
var classN=".views-row5"
$('.carousel-inner li').each(function()
  {$(this).find(classN).addClass('hello');});
 });
.hello {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-inner">
  <li>
     <div class="views-row4">1</div>
     <div class="views-row5">2</div>
  </li>
  <li>
     <div class="views-row4">1</div>
     <div class="views-row5">2</div>
  </li>
</div>

答案 3 :(得分:2)

试试这段代码:

jQuery(document).ready(function($) {
   var classN="views-row5"
   $('.' + classN).addClass('hello');
});