前端調試指南指北

作人作事,安全第一

目錄

1. 防止input回車提交表單Form

描述: form表單中存在button和table,table中含有input搜索框,在input中輸入內容後,按回車鍵(Enter鍵),會自動觸發form表單提交。css

form主要代碼以下:html

<form id="form" method="post">
    <div class="main-actions">
        <div class="row">
            <div class="col-sm-6">
                <button class="btn btn-wf-primary" id="search"><i class="be-icon fa fa-refresh"></i>搜索</button>
            </div>
        </div>
    </div>
    
    <div class="main-content">
        <table class="table" id="user_table">
            <thead>
                <tr>
                    <th width="100px">用戶ID</th>
                    <th width="100px">用戶姓名</th>
                    <th width="100px">用戶電話</th>
                </tr>
            </thead>
            <tbody>
                <tr class="searchTr">
                    <td><input type="text" class="form-control" name="user_id"></td>
                    <td><input type="text" class="form-control" name="user_name"></td>
                    <td><input type="text" class="form-control" name="user_phone"></td>
                </tr>
            </tbody>
        </table>
    </div>
</form>
複製代碼

緣由:

當button的type="submit"時(默認爲submit),input文本框(input type="text")輸入後,按回車鍵(Enter鍵)將觸發提交。java

當button的type="button"時,input文本框輸入後,按回車鍵不會觸發提交。jquery


代碼簡單示例:form表單中含table也是相似的狀況ios

<!DOCTYPE html>
<html>
<head>
    <title>防止input回車提交表單Form演示</title>
</head>
<body>
	<form method="post">
		請輸入用戶ID: <input type="text" name="userid" id="userid" />
		<br>	
		請輸入用戶姓名: <input type="text" name="username" id="username" />
		<br>
		<!-- 1. 無type屬性或type屬性值爲submit時,在input中按Enter鍵都將觸發提交操做 -->
		<!-- 2. type屬性值爲button時,在input中按Enter鍵不觸發提交操做 -->
		<button type="submit" onclick="commit_onclick()">點擊提交</button>
	</form>	
	<script>
		function commit_onclick() {
			var userid = document.getElementById("userid").value;
			var username = document.getElementById("username").value;
			window.alert('Hello ' + userid + '[' + username + ']');
		}
	</script>
</body>
</html>
複製代碼

2. Uncaught TypeError: $(...).bootstrapTable is not a function

出現這種錯誤的緣由,多是:

<1> jQuery和bootstrap順序顛倒程序員

<2> js文件重複導入npm

<3> 沒有初始化bootstrapTable,直接refreshbootstrap

<4> bootstrap版本和bootstrap-table版本不匹配瀏覽器


<1> jQuery和bootstrap順序顛倒

引入js時,jQuery必須放在最前面,而後是bootstrap,順序不能顛倒。安全

Bootstrap官網(Bootstrap 4.0版本)給出了的模板,以下:

( 連接爲 : v4.bootcss.com/docs/4.0/ge…

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdn.bootcss.com/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://cdn.bootcss.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
  </body>
</html>

複製代碼

涉及到bootstrap-table,bootstrap-table-zh-CN(漢化),給出正確的導入順序,以下:

<script src="${pageContext.request.contextPath}/js/jquery-3.1.0.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap-table.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap-table-zh-CN.min.js"></script>
複製代碼

<2> js文件重複導入

在同一個html或jsp文件中,js文件通常不會重複導入,沒有人會這麼幹,除非先後放置位置不一樣,沒有發現,刪掉重複的js便可。

通常出現js文件重複導入都是在html或jsp文件有嵌套的狀況,以下所示:

index.jsp文件 : 已經導入了bootstrap相關js文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Hello, RangDanDanFei</title>
</head>
<body>
<%@ include file="/jsp/head.jsp" %>
<h1>Hello, RangDanDanFei</h1>

<script src="${pageContext.request.contextPath}/js/jquery-3.1.0.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap-table.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap-table-zh-CN.min.js"></script>
</body>
</html>
複製代碼

head.jsp文件 : 重複導入了bootstrap相關js文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div class="panel panel-default">
    <div class="panel-heading"></div>
    <div class="panel-body">
        <div class="row">
            <div class="col-sm-2"></div>
        </div>
    </div>
</div>

<script src="${pageContext.request.contextPath}/js/jquery-3.1.0.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap-table.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap-table-zh-CN.min.js"></script>
複製代碼

<3> 沒有初始化bootstrapTable,直接refresh

Stack Overflow有該問題的描述以及解答,連接地址爲:stackoverflow.com/questions/5…

<4> bootstrap版本和bootstrap-table版本不匹配

嘗試升級其中一個版本

3. input文本框禁止輸入

有兩種方式:

<1> 增長readonly屬性:表示該輸入域只能讀,不能寫,可複製,可選擇,可接收焦點,後臺會接收到傳值。

<input type="text" name="inputname" readonly="readonly" />

注意:readonly屬性只能與type="text"配合使用
複製代碼

<2> 增長disabled屬性:不可編輯,不可選擇,不能接收焦點,後臺不會接收到傳值,頁面顯示置灰。

<input type="text" name="inputname" disabled="disabled" /> 
複製代碼

4. input文本框自動清除用戶輸入記錄

增長autocomplete="off"屬性,便可在每次從新請求頁面時,自動清空用戶輸入記錄。

<input type="text" autocomplete="off" />

相對應:
autocomplete="on"或者默認沒有autocomplete屬性,每次不會自動清空用戶輸入記錄。
複製代碼

5. input文本框輸入值的監聽

總結:

<1> 文本框輸入完成,失去焦點,觸發change事件監聽:

$('#id').on('change', function() {...})
或 $('#id').change(function() {...})
或 $('#id').bind('change', function() {...});
複製代碼

<2> 文本框輸入值實時變化,觸發input事件或者propertyChange事件監聽:

$('#id').on('input propertychange', function() {...})
或
$('#id').bind('input propertychange', function() {...});
複製代碼

<1> 失去焦點的監聽:即在文本框輸入完成後,將焦點切出,觸發change事件

觸發change事件,須要知足如下兩個條件:

1. 當前對象屬性改變,而且是由鍵盤或鼠標事件觸發的(腳本觸發的無效)
2. 當前對象失去焦點
複製代碼

三種實現方式以下:

1. $('#id').on('change', function() {...});
2. $('#id').change(function() {...});
3. $('#id').bind('change', function() {...});

複製代碼

擴展:

change事件還能夠用於如下事件:

1. select選擇框:選中項發生變化

2. checkbox複選框:選中狀態發生變化
    <input type="checkbox" id="checkboxId" />

3. radio單選按鈕:選中狀態發生變化
    <div>
        <input type="radio" name="colors" value="red"/>紅色<br>
        <input type="radio" name="colors" value="blue"/>藍色<br>
        <input type="radio" name="colors" value="green"/>綠色<br>	
    </div>
複製代碼

示例代碼以下:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>input文本框輸入失去焦點的監聽</title>
</head>
<body>
	<input type="text" id="textId" placeholder="請輸入字符!" /><i id="textTip"></i>
	<br>

	<select id="selectId">
		<option value="bejing">北京</option>
		<option value="shanghai">上海</option>
		<option value="shenzhen">深圳</option>
	</select>
	<i id="selectTip"></i>
	<br>

	<input type="checkbox" id="checkboxId" /><i id="checkboxTip"></i>
	<br>

	<div id="radioId">
		請選擇你喜歡的顏色!<br>
		<input type="radio" name="colors" value="red"/>紅色<br>	
		<input type="radio" name="colors" value="blue"/>藍色<br>
		<input type="radio" name="colors" value="green"/>綠色<br>	
	</div>
	<i id="radioTip"></i>
	
	<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
	<script>
		$(document).ready(function() {
			$('#textId').on('change', function(){
				$('#textTip').html("共輸入了 " + $(this).val().length + " 個字符!");
			});

			$('#selectId').on('change', function() {
				$('#selectTip').html("您選擇的城市是" + $(this).find("option:selected").text());
			});

			$('#checkboxId').on('change', function() {
				if (document.getElementById("checkboxId").checked == true) {
					$('#checkboxTip').html("您已經選中");
				} else {
					$('#checkboxTip').html("您已經取消選擇");
				}
			});

			$('#radioId').on('change', function() {
				var radios = document.getElementsByName('colors');
				for (var i = 0, len = radios.length; i < len; i++) {
					if (radios[i].checked) {
						$('#radioTip').html("您喜歡的顏色是" + radios[i].nextSibling.data);
						break;
					}
				}
			});
		});
	</script>
</body>
</html>
複製代碼

失去焦點監聽示例代碼執行展現

<2> 實時監聽:實時監聽文本框中值的變化,觸發input事件或者propertyChange事件

input事件:是HTML5的標準事件,通常瀏覽器都支持。當input的value發生變化時,不管是鍵盤輸入、鼠標粘貼或腳本修改都能觸發。IE9如下版本不支持input事件。

propertychange事件(IE專屬):只要當前對象屬性發生改變,都會觸發,不只僅會監聽到input的value屬性,還包括其餘的屬性標籤,好比:span元素的style屬性改變。同時在事件發生時還能夠用 event.propertyName 訪問到改變的屬性名。

(因爲IE9如下不支持input事件,因此要用到IE的專屬propertychange事件)
複製代碼

實現方式:

1. $('#id').on('input propertychange', function() {...});
2. $('#id').bind('input propertychange', function() {...});
複製代碼

示例代碼:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>input文本框輸入實時監聽</title>
</head>
<body>
	<input type="text" id="textId" placeholder="請輸入字符!" /><i id="textTip"></i>

	<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
	<script>
		$(document).ready(function() {
			$('#textId').on('input propertychange', function() {
				$('#textTip').html("您已經輸入了 " + $(this).val().length + " 個字符!");
			});
		});
	</script>
</body>
</html>
複製代碼

實時監聽示例代碼執行展現

6. 獲取表格指定的行,列

先看一下HTML構建簡單表格的結構:

simple_table_structure

對簡單表格操做總結:

  1. 獲取表格行數
形式1: $('#tableId tr').length
形式2: $('#tableId').find('tr').length
複製代碼
  1. 獲取表格列數
形式1: $('#tableId th').length
形式2: $('#tableId tr:eq(1) td').length
形式3: $('#tableId tr:eq(1)').find('td').length
注意:表頭行標籤形式爲:
<thead>
  <tr>
      <th></th>
      <th></th>
  </tr>
</thead>
<tr>中嵌套的標籤是<th>,不是<td>
因此上面形式2,形式3中選擇器:eq(index)的index值不是0,即跳過表頭
複製代碼
  1. 獲取表格某一行的值
例如:獲取表格第二行的值(表頭算表的第一行)
形式1: $('#tableId tr:eq(1)').text();
形式2: $('#tableId tr').eq(1).text();
形式3: $('#tableId').find('tr').eq(1).text();
複製代碼
  1. 獲取表格某一行某一列的值
例如:獲取表格第二行第一列的值(表頭算表的第一行)
形式1: $('#tableIndex tr:eq(1) td:eq(0)').text()
形式2: $('#tableIndex tr').eq(1).find('td:eq(0)').text())
形式3: $('#tableIndex').find('tr').eq(1).find('td').eq(0).text())
複製代碼

說明:

1. jQuery選擇器:
<1> $('#tableId tr') 表示:匹配id爲"tableId"的表格下的<tr>元素
<2> $(':eq(index)') 表示:選擇器選取帶有指定index值的元素,index值從0開始,全部第一個元素的index值是0
    若是index是負數,則從集合中的最後一個元素倒着往回計數
    例如:$('#tableId tr:eq(-1)') 表示:id爲"tableId"的表格的倒數第一行

2. jQuery方法:
<1> .eq(index) 表示:匹配元素集合中索引爲index的元素上,index值從0開始,表示第一個元素,
    若是index是負數,則從集合中的最後一個元素倒着往回計數
複製代碼

代碼示例:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <title>Hello, Simple Table!</title>
  </head>
  <body>
    <table id="usertable" border="1">
      <thead>
        <tr>
          <th>ID</th>
          <th>姓名</th>
          <th>職業</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>讓蛋蛋飛</td>
          <td>尼古拉斯蛋蛋</td>
          <td>程序員</td>
        </tr>
        <tr>
          <td>夏至未至</td>
          <td>李木子</td>
          <td>醫生</td>
        </tr>
      </tbody>
    </table>
    <br>
    <div id="rowSize"></div>
    <div id="colSize"></div>
    <div id="tipth"></div>
    <div id="tiptr"></div>
    <div id="tiptd"></div>
    <div id="tiptrtd"></div>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script>
      $(document).ready(function() {
        $('#rowSize').html("此表共" + $('#usertable tr').length + "行");
        $('#colSize').html("此表共" + $('#usertable th').length + "列");
        $('#tipth').html("此表表頭的值爲:" + $('#usertable th').text());
        $('#tiptr').html("此表第二行(表頭爲第一行)的值爲:" + $('#usertable tr:eq(1)').text());
        $('#tiptd').html("此表第一列的值爲:" + $('#usertable td:nth-child(1)').text());
        $('#tiptrtd').html("此表第三行第二列的值爲:" + $('#usertable tr:eq(2) td:eq(1)').text());
      });
    </script>
  </body>
</html>
複製代碼

simple_table

說明:
:nth-child(n)是CSS3選擇器,匹配屬於其父元素的第 N 個子元素,不論元素的類型。不支持IE8及更早版本。

實例解析:
$('#usertable td:nth-child(1)'):在usertable表中td的父元素爲tr,則td是子,tr是父,
表示匹配tr中第一個子元素td,表中有兩行<tr>包含<td>,所以最終會匹配到usertable表中第一列的值(不含表頭)。

延伸:
:nth-child(n)中 n 能夠爲公式,(an + b)表示:週期的長度,n是計數器(從0開始),b是偏移量。
示例:指定了下標是3的倍數的全部p元素的背景色
p:nth-child(3n+0) {
    backgroup:#ff0000;
}
複製代碼

7. 獲取表格中控件的值

有兩種方式:以#6中的表格爲例(表頭爲第一行)

方式一:

例如:獲取usertable表第二行中id="userid"或name="userid"的文本框(input text)的值
$('#usertable tr:eq(1)').find('#userid').val();
或者 
$('#usertable tr:eq(1)').find('input[name="userid"]').val();
複製代碼

方式二:

例如:只知某表的某行中文本框組件id爲"userid",表的相關信息不知,想要獲取該行中文本框name="userjob"的值
$('#userid').closest('tr').find('input[name="userjob"]').val();
複製代碼

某表某行input id=

說明:
jQuery的closest()方法:
.closest(selector) : 從當前元素開始,沿DOM樹向上遍歷,直到找到一個匹配selector的元素爲止,而後返回一個包含該找到元素的jQuery對象。
(未找到的話,則返回0個)

實例解析:
$('#userid').closest('tr').find('input[name="userjob"]').val(): 選擇器先匹配找到id="userid"的元素,
而後從該元素開始,沿DOM樹向上找<tr>元素,匹配到一個後返回,即定位到了該行,
而後用find找出該行name="userjob"的文本框,取值。

延伸:
.closest(selector, DOMContext) : 表示從當前元素開始,在指定的DOM元素範圍中遍歷搜索。
示例:
DOM樹結構以下:
<ul>
  <li id="i1">I1</li>
  <li id="i2">I2
    <ul>
      <li class="item-a">Item A</li>
      <li class="item-b">Item B</li>
      <li class="item-c">Item C</li>
    </ul>
  </li>
  <li id="i3">I3</li>
</ul>  

$('li.item-a').closest('ul', document.getElementById('i2')): 表示從Item A元素開始,指定遍歷搜索的DOM範圍是id="i2"的列表元素集合。
複製代碼

8. 表頭thead隨表體tbody橫向滾動

問題描述:

瀏覽器的窗口切換事後,發現表格的表頭不隨表體橫向滾動,致使列標題與實際列數據錯位。

解決方法:

  1. HTML編寫的簡單表格: 用<div>標籤包裹<table>標籤,並設置div的樣式爲:overflow-x: auto;

  2. bootstrapTable插件初始化的表格,去掉height屬性

代碼示例:

See the Pen thead_horizontal_scroll by rangdandanfei (@rangdandanfei) on CodePen.

9. 表頭固定,不隨滾動

現象描述:

當表格出現垂直滾動條時,讓表頭固定住,不隨垂直滾動條上下移動。

表格垂直滾動時表頭固定

解決方式:

方式一:BootstrapTable實現的table : 在<table>標籤上增長data-height屬性值,便可固定表頭。【推薦這種方式】

<table id="table" data-toggle="table" data-height="460" data-url="https://examples.wenzhixin.net.cn/examples/bootstrap_table/data">
說明:data-url用來給table提供數據
複製代碼

BootstrapTable插件爲咱們提供了很好示例,見官方連接:examples.bootstrap-table.com/#options/ta…

注意:使用data-height屬性時,官方API給出了以下提示:

Note that if there are multiple tables on a page and the height option is set at the same time, you need to add the id attribute to each table, otherwise, the window resize will not work properly.

即:一個頁面有多個表時,且表都設置了"data-height"屬性值,則要給每一個表添加"id"屬性,不然瀏覽器窗口大小切換調整,表格就不能正常工做。
複製代碼

代碼示例:

<!DOCTYPE html>
<html>
<head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://unpkg.com/bootstrap-table@1.15.4/dist/bootstrap-table.min.css" rel="stylesheet">
    <title>BootstrapTable表頭固定</title>
</head>
<body>
    <table id="table" data-toggle="table" data-height="460" data-url="https://examples.wenzhixin.net.cn/examples/bootstrap_table/data">
        <thead>
            <tr>
                <th data-field="id">ID</th>
                <th data-field="name">Item Name</th>
                <th data-field="price">Item Price</th>
            </tr>
        </thead>
    </table>
    <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
    <script src="https://unpkg.com/bootstrap-table@1.15.4/dist/bootstrap-table.min.js"></script>
</body>
</html>
複製代碼

方式二:頭身分離法

基於Bootstrap的CSS樣式實現頭身分離,表頭固定,不用js腳本:

  1. 使用兩個<table>,一個只有表頭<thead>,一個只有表體<tbody>,分別用<div>包裹

  2. 表體的div增長class="pre-scrollable"實現,即帶滾動條

    表體的div增長style="height:100px; margin-top:-22px;"樣式

說明:margin-top: 設置上邊距,調整設置爲一個負值,使表頭div底線與表體div頂線重合,即兩個表拼接成一個表
         當錶行內容超過設置的heigh值時,出現垂直滾動條,這時上下滾動時,表頭固定,表體隨動。
複製代碼

代碼示例:

<!-- 導入bootstrap.css樣式 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
<div>
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Heading</th>
                <th>Heading</th>
                <th>Heading</th>
            </tr>
        </thead>
    </table>
</div>
<div class="pre-scrollable" style="height:100px; margin-top: -22px;">
    <table class="table table-striped table-hover">
        <tbody>
            <tr>
                <td>RowCell</td>
                <td>RowCell</td>
                <td>RowCellg</td>
            </tr>
            <tr>
                <td>RowCell</td>
                <td>RowCell</td>
                <td>RowCellg</td>
            </tr>
            <tr>
                <td>RowCell</td>
                <td>RowCell</td>
                <td>RowCellg</td>
            </tr>
        </thead>
    </table>
</div>
複製代碼
相關文章
相關標籤/搜索