我有一个这样的清单:
<ul id="recipes">
<li><a href='xxx'>Apple Pie</a></li>
<li><a href='xxx'>Almond Slice</a></li>
<li><a href='xxx'>Banana Cake</a></li>
<li><a href='xxx'>Carrot Cake</a></li>
</ul>
我需要像这样添加带有jQuery的类:
<ul id="recipes">
<li class="a"><a href='xxx'>Apple Pie</a></li>
<li class="a"><a href='xxx'>Almond Slice</a></li>
<li class="b"><a href='xxx'>Banana Cake</a></li>
<li class="c"><a href='xxx'>Carrot Cake</a></li>
</ul>
目标是使用this thread的答案按字母顺序对列表进行分组,这需要先添加类。
答案 0 :(得分:2)
$("#recipes li").each(function() { // <-- Run over each li
var s = $(this).find("a").html().charAt(0) // <-- takes the first character of link
$(this).addClass(s.toLowerCase()) // <-- Add the character as a class to the li
})
$("#recipes li").each(function() {
var s = $(this).find("a").html().charAt(0)
$(this).addClass(s.toLowerCase())
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="recipes">
<li><a href='xxx'>Apple Pie</a></li>
<li><a href='xxx'>Almond Slice</a></li>
<li><a href='xxx'>Banana Cake</a></li>
<li><a href='xxx'>Carrot Cake</a></li>
</ul>
&#13;
答案 1 :(得分:1)
您可以循环每个li
并获取内部a
的第一个字母并将其转换为小写
$('ul li').each(function() {
$(this).addClass($(this).find('a').text()[0].toLowerCase())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="recipes">
<li><a href='xxx'>Apple Pie</a></li>
<li><a href='xxx'>Almond Slice</a></li>
<li><a href='xxx'>Banana Cake</a></li>
<li><a href='xxx'>Carrot Cake</a></li>
</ul>
答案 2 :(得分:0)
将列表放在变量中,遍历变量并添加一个类作为列表中每个成员的文本值的子字符串。
func setupTimePicker(){
datePickerView.datePickerMode = UIDatePickerMode.time
datePickerView.removeFromSuperview()
timeTextField.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(self.datePickerValueChanged(sender:)), for: .valueChanged)
}
func datePickerValueChanged(sender:UIDatePicker) {
var date = Date()
let calendar = Calendar.current
date = sender.date;
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
timeTextField.text = String(format: "%02d", hour) + ":" + String(format: "%02d", minutes)
}
答案 3 :(得分:0)
尝试下面列出的代码:
$(document).ready(function() {
$("ul > li").each(function () {
var text = $(this).find("a").text();
$(this).addClass(text[0].toLowerCase());
});
});