javaScript-practice2019-0603

1.搜索框示例html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>搜索框示例</title>

</head>
<body>
    <!--onfocus        元素得到焦點。               // 練習:輸入框-->
    <!--onblur         元素失去焦點。 -->
    <input id="d1" type="text" value="請輸入關鍵字" onblur="blur()" onfocus="focus()">
<script>
function focus(){
    var inputEle=document.getElementById("d1");
    if (inputEle.value==="請輸入關鍵字"){
        inputEle.value="";
    }
}

function blur(){
    var inputEle=document.getElementById("d1");
    var val=inputEle.value;
    if(!val.trim()){            //去掉元素兩端的空格
        inputEle.value="請輸入關鍵字";
    }
}
</script>
</body>
</html>
View Code

 2. 城市聯動app

1.定義data數據
2.經過ID獲取標籤
3.定義onchange()函數,先獲取省名,再獲得市名
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>select聯動</title>
</head>
<body>
<select id="province">
  <option>請選擇省:</option>
</select>

<select id="city">
  <option>請選擇市:</option>
</select>

<script>
  data = {"河北省": ["廊坊", "邯鄲"], "北京": ["朝陽區", "海淀區"], "山東": ["威海市", "煙臺市"]};
    var p = document.getElementById("province");  //1.經過ID獲取標籤
    var c = document.getElementById("city");
  
  for (var i in data) {
    var optionP = document.createElement("option");     //a 建立節點,經過標籤名建立節點
    optionP.innerHTML = i;      //b XX.innerHTML 獲取文本節點的值:
    p.appendChild(optionP);     //c 將optionP的值追加一個子節點(做爲最後的子節點)
  }

  p.onchange = function () {
    var pro = (this.options[this.selectedIndex]).innerHTML; //a 選擇不一樣的省份
    var citys = data[pro];                  //b  經過省份,獲取市名
    c.innerHTML = "";               //c 清空option,下面的for循環添加城市內容

    for (var i=0;i<citys.length;i++) {
      var option_city = document.createElement("option");
      option_city.innerHTML = citys[i];
      c.appendChild(option_city);
    }
  }
</script>
</body>
</html>
View Code

3.ide

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息