如何从子元素文本值向父类添加类? jQuery的

时间:2015-10-20 07:39:24

标签: javascript jquery html css

我有一个包含子元素的列表。我想将.post-meta-boxcolor的值添加到父li

<ul class="course-list">
    <li>

     <div class="course-content">
      <p class="post-meta post-meta-level">Level 2</p>
      <p class="post-meta post-meta-boxcolor">orange</p>
     </div>

    </li>

    <li>

     <div class="course-content">
      <p class="post-meta post-meta-level">Level 2</p>
      <p class="post-meta post-meta-boxcolor">red</p>
     </div>

    </li>

    <li>

     <div class="course-content">
      <p class="post-meta post-meta-level">Level 2</p>
      <p class="post-meta post-meta-boxcolor">lightblue</p>
     </div>

    </li>


</ul>

如何根据class =“post-meta-boxcolor”文本或值将类添加到父li。

我想要的结果是:

<ul class="course-list">
    <li class="orange">

     <div class="course-content">
      <p class="post-meta post-meta-level">Level 2</p>
      <p class="post-meta post-meta-boxcolor">orange</p>
     </div>

    </li>

    <li class="red">

     <div class="course-content">
      <p class="post-meta post-meta-level">Level 2</p>
      <p class="post-meta post-meta-boxcolor">red</p>
     </div>

    </li>

    <li class="lightblue">

     <div class="course-content">
      <p class="post-meta post-meta-level">Level 2</p>
      <p class="post-meta post-meta-boxcolor">lightblue</p>
     </div>

    </li>


</ul>

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

您可以使用addClass方法将回调作为参数,如

//Add bellow line in your manifest 

<manifest ... >
  <uses-permission android:name="android.permission.BLUETOOTH" />
  ...
</manifest>
$('.course-list li').addClass(function() {
  return $(this).find('.post-meta-boxcolor').text()
})
.orange {
  color: orange;
}
.red {
  color: red;
}
.lightblue {
  color: lightblue;
}

答案 1 :(得分:1)

您可以使用:

$('.course-list li').addClass(function(){
     return $(this).find('.post-meta-boxcolor').text().replace(/\s/g, '');
});