jquery动态增加text元素以及删除文本内容实例代码 |
这段代码是通过jquery动态增加限定数额的text(本例为5个) ,以及清除文本内容,用到了after()方法追加元素 。 <!--以下为script代码开始--> 复制代码 代码如下: <script> $(document).ready(function(){ var spotMax = 5;//限定添加text元素的总个数 var afterId = 0;//要追加元素的id var newId=1;//新生成text的id if($(table#vote).size() >= spotMax) {} $("#btnAddOption").click(function(){ afterId++; newId=afterId+1; addSpot(this, spotMax,afterId,newId); }); }); //添加选项方法 function addSpot(obj, sm,afterId,newId) { if($(tr.spot).size() < sm){ $(#vote_+afterId).after( <tr id="vote_+newId+" class="spot"><th>+afterId+</th> + <td><input type="text" id="txtInput_+afterId+" class="input-text" value="" size="40" name="names" /></td> + </tr>); $(":text[id^=txtInput_]").val("输入文本...");//给新增的文本赋予初始值 } else{ alert("最多只能添加5项投票!"); } }; //重置选项 $("input#btnResetOption").click(function(){ $(":text[id^=txtInput_]").val("");//清空文本内容 }); </script> <!--以下为script代码结束--> <!--以下为html代码块开始--> 复制代码 代码如下: <form method=post id="updateForm" action="admin/vote/doVote"> <table cellpadding=0 cellspacing=0 width="100%" class="table_form"> <tr> <th width="140">投票名称</th> <td> <input type="text" id="txtName" name="name" class="input-text" value="" size="85"/> </td> </tr> <tr> <th width="140">投票描述</th> <td> <textarea id="txtDescribe" class="input-text" name="remark" cols="85" ></textarea> </td> </tr> <tr> <th width="140">开始时间</th> <td> <input type="text" id="dateMin" class="input-text" value="" name="startDate" size="40" readonly="readonly"/> </td> </tr> <tr> <th width="140">结束时间</th> <td> <input type="text" id="dateMax" class="input-text" name="endDate" size="40" readonly="readonly"/> </td> </tr> <tr> <th width="140">是否多选</th> <td> <input type="radio" id="txtEndTime" name="isSelect" value="0" size="40"/>单选 <input type="radio" id="txtEndTime" name="isSelect" value="1" size="40"/>多选 </td> </tr> <tr id="vote_1"> <th width="140">投票选项</th> <td> <input type="button" id="btnAddOption" name="btnAddOption" class="button" value="添加选项"/> <input type="reset" id="btnResetOption" name="btnResetOption" class="button" value="重置选项"/> </td> </tr> <tr id="save"> <th></th> <td align="left"> <input type="submit" id="btnSave" name="btnSave" class="button" style="width:50px" value="保存"/> <input type="submit" id="btnClose" name="btnClose" class="button" style="width:50px" value="取消"/> </td> </tr> </table> </form> <!--以下为html代码块开始--> 以下是运行效果: ![]() |