做项目的时候遇到一个问题就是根据用户选择生日自动生成判断显示星座,最开始我用条件语句判断显示,但是太冗长了,不简洁,然后我就在网上找到了一个方法特别简洁好用,然后根据需求自己写了一下。废话不多说,上代码:
html部分:
<table>
<tbody>
<tr>
<td>生日:</td>
<td>
<input name="birth" id="birth" class="easyui-datebox" type="text" />
</td>
<td>
<input id="constellation" name="constellation" type="text" class="easyui-textbox" disabled="disabled">
</td>
</tr>
</tbody>
</table>
js部分:
$("#birth").datebox({
onSelect: function(date) {
//alert(date.getFullYear()+":"+(date.getMonth()+1)+":"+date.getDate());
var m = date.getMonth() + 1;
var d = date.getDate();
$("#constellation").textbox("setValue", "魔羯座水瓶座双鱼座牡羊座金牛座双子座巨蟹座狮子座处女座天秤座天蝎座射手座魔羯座".substr(m * 3 - (d < "102223444433".charAt(m - 1) - -19) * 3, 3));
}
});
最后效果如下:
substr() :截取字符串中的某部分。
语法:stringObject.substr(start,length)
start:必需。要抽取的子串的起始下标。必须是数值。如果是负数,那么该参数声明从字符串的尾部开始算起的位置。也就是说,-1 指字符串中最后一个字符,-2 指倒数第二个字符,以此类推。
length:可选。子串中的字符数。必须是数值。如果省略了该参数,那么返回从 stringObject 的开始位置到结尾的字串。
charAt() :返回指定位置的字符。
语法:stringObject.charAt(index)
index:字符串中某个位置的数字(字符在字符串中的下标,从0开始)。