在我的JSON
中,我得到一个字符串:
selectedDays: "Mon, Tue, Wed, Thur, Fri, Sat"
我需要对此进行分解,以便我可以添加某种形式的loop
来添加class
,但是我不知道该怎么做。
是这样,所以我可以在loop
$('button[name=SOME_NAME]).addClass('.btn-primary');
无法弄清楚,以前从未使用过JSON
数据。
在console.log
中返回的完整数据
{
endTime: "01:02",
endTimeHr: "01",
endTimeMin: "02",
number: "00000001",
position: "1",
selectedDates: "All days of the month",
selectedDays: "Mon, Tue, Wed, Thur, Fri, Sat",
selectedMonths: "Jan, Aug",
startTime: "01:01",
startTimeHr: "01",
startTimeMin: "01",
timeRange: "-w",
timeType: "specificTime"
};
当前HTML每日按钮
<div class="form-horizontal" id="selectWeekdaysSection">
<div class="form-group">
<div class="col-md-offset-2 col-lg-4">
<button id="mon" name="weekdaysbutton" class="btn btn-default" type="button" value="Mon">Mon</button>
<button id="tue" name="weekdaysbutton" class="btn btn-default" type="button" value="Tue">Tue</button>
<button id="wed" name="weekdaysbutton" class="btn btn-default" type="button" value="Wed">Wed</button>
<button id="thur" name="weekdaysbutton" class="btn btn-default" type="button" value="Thur">Thur</button>
<button id="fri" name="weekdaysbutton" class="btn btn-default" type="button" value="Fri">Fri</button>
<button id="sat" name="weekenddaysbutton" class="btn btn-default" type="button" value="Sat">Sat</button>
<button id="sun" name="weekenddaysbutton" class="btn btn-default" type="button" value="Sun">Sun</button>
</div>
</div>
</div>
答案 0 :(得分:4)
STEPS:
const json = {
selectedDays: "Mon, Tue, Wed, Thur, Fri, Sat"
}
let selectedDays = json.selectedDays.toLowerCase().replace(/ /g, '').split(',')
selectedDays.forEach(day => {
$('button#' + day).addClass('.btn-primary')
})
// Log the classes
$('button').each((i, e) => {
console.log($(e).attr('id'), $(e).attr('class'))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="mon" name="weekdaysbutton" class="btn btn-default" type="button" value="Mon">Mon</button>
<button id="tue" name="weekdaysbutton" class="btn btn-default" type="button" value="Tue">Tue</button>
<button id="wed" name="weekdaysbutton" class="btn btn-default" type="button" value="Wed">Wed</button>
<button id="thur" name="weekdaysbutton" class="btn btn-default" type="button" value="Thur">Thur</button>
<button id="fri" name="weekdaysbutton" class="btn btn-default" type="button" value="Fri">Fri</button>
<button id="sat" name="weekenddaysbutton" class="btn btn-default" type="button" value="Sat">Sat</button>
<button id="sun" name="weekenddaysbutton" class="btn btn-default" type="button" value="Sun">Sun</button>
答案 1 :(得分:2)
如果还没有的话,您要做的第一件事就是parse the JSON data,以便可以将其用作JavaScript对象。之后,您应该能够引用selectedDays
属性,并使用JavaScript的split字符串操作方法将数据转换为.each()可以迭代的内容