JS对html中的一些操作


1 动态增加表格行


这经常在Ajax应用中用到,下面的例子:

<html>
  <head><title>动态增加行</title>
  </head>
  <body>
    <table border="1">
       <tr><td>姓名</td><td>地址</td></tr>
       <tbody id="mainbody"></tbody>
  </table>
<input type="button" value="增加行" οnclick="addCell()"/>
</body>

<script type="text/javascript">
  function addCell(){
   var cell = document.createElement("tr");

   var row1 = document.createElement("td");
   var row2 = document.createElement("td");

   var textNode1 = document.createTextNode("zidoing")
   var textNode2 = document.createTextNode("xiamen");
   row1.appendChild(textNode1);
   row2.appendChild(textNode2);
   cell.appendChild(row1);
   cell.appendChild(row2);
   var mainbody = document.getElementById("mainbody");
   mainbody.appendChild(cell);
  }
 </script>
</html>

在<tbody>中添加了行之后如何删除呢?

docuement.getElementById("mainbody").innerTHML=''

即可!


2 获取<input>控件的值

(1)<input>不在<form>中时


(2)<input>在<form>中时

<from name="formname" id="formid">
<input name="inputname" id="inputid" value="">
</form>

<script type="text/javascript">
  //获取输入框中的值
  var inputvalue = document.formname.inputname.value;
</script>


3 获取<select>中<option>的值

示例1:获取选中的<option>值

<select name="selectname" id="selectid" οnchange="show(this.options[this.options.selectedIndex].value)">
<option value="0">aaa</option>
...
</select> 

<script type="text/javascript">
function show(optionValue) {

}
</scritp>

其中optionValue就是所选中的<option>的value值。


示例2:当<select>在表单<form>中时

<form name="formname" id="formid">
<select name="selectname" id="selectid" οnchange="show()">
  <option value="0">aa</option>
  <option value="1">bb</option>
</select>

<script type="text/javascript">
function show() {
  //获得用户选中的项的索引 
  var index = window.document.formname.selectname.selectedIndex; 
  //根据索引获得该选项的value值 
  var optionvalue = window.document.formname.selectname.options[index].value;

}
</script>

示例3:当<select>不在表单<form>中时

//如果select并非表单元素,则如下: 
var index = window.document.getElementById("selectid").selectedIndex; 
var val = window.document.getElementById("selectid").options[index].value;
 
//*根据index获取选中项的Text值,即在下拉列表中显示的选项文本 
var vname=window.document.getElementById("sel").options[index].text


示例4:获取所有<option>值

function showAllvalues() {
	var selectId = document.all.selectid;
	for (var i = 0; i < selectId.length; i++) {
	    //window.document.getElementById("selectid").options[i].value
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值