日期:2014-05-16  浏览次数:20472 次

js处理json和字符串示例

js处理json格式的插入、修改、删除,以及字符串的比较等常用操作


demo 1: 

json格式的插入、删除

<html>
	<head>
		<title></title>
		<script language="javascript">
			function change(){
				var obj=document.getElementById("floor");
				if (document.getElementById("qu").value=="1"){
					var t=document.createElement("OPTION");
					t.text="第五楼";
					t.value="5";
					obj.add(t);
				}else if(document.getElementById("qu").value=="2"){
					for(var i=0; i<obj.length;i++){
						if(obj.options[i].value=="5"){
							obj.remove(i);
							return;
						}
					}
				}
			}
		</script>
	</head>
	<body>
	<form id="form1" name="form1" method="post" action="">
	
	  <select multiple="multiple" name="qu" id="qu" onchange="change()" style="width: 150px; height: 300px;">
	    <option value="请选择所在区">--请选择所在区--</option>
	    <option value="1">南开区</option>
	    <option value="2">红桥区</option>
      </select>
      
	  <select multiple="multiple" name="floor" id="floor" style="width: 150px; height: 300px;">
          <option value="请选择楼层">--请选择楼层--</option>
          <option value="1">第一楼</option>
          <option value="2">第二楼</option>
          <option value="3">第三楼</option>
          <option value="4">第四楼</option>
        </select>
    </form>
	
	</body>
</html>
运行结果:




demo2:

<!DOCTYPE html>
<html>
	<script language="javascript">
		function toLeft() {
			var list1 = document.getElementById("list1");
			var list2 = document.getElementById("list2");
  
			for (var i = list2.options.length-1; i >= 0 ; i--) {
				if(list2.options[i].selected ==true){
					var op = document.createElement("option");
					op.text = list2.options[i].text;
					op.value = list2.options[i].value;
					list1.add(op);
					list2.remove(i);
				}
			}
		}

		function toRight() {
			var list1 = document.getElementById("list1");
			var list2 = document.getElementById("list2");
  
			for (var i = list1.options.length-1; i >= 0 ; i--) {
				if(list1.options[i].selected ==true){
					var op = document.createElement("option");
					op.text = list1.options[i].text;
					op.value = list1.options[i].value;
					list2.add(op);
					list1.remove(i);
				}
			}
		}

		function submit() {
			var list2 = document.getElementById("list2");
			var innerStr = "";
			for (var i = 0; i < list2.options.length; i++) {
				innerStr += i + " - " + list2.options[i].text + " : " + list2.options[i].value + "</br>";
			}
			var wt = document.getElementById("wt");
			wt.innerHTML = innerStr;
		}
	</script>
</head>

<body>
<div>
<select multiple="multiple" id="list1" style="width: 500px; height: 100px;>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

<input type="button" value=">" onclick="toRight();submit()"/>  
<input type="button" value="<" onclick="toLeft();submit