JavaScript学习06(操作BOM和表单)

时间:2022-04-12 19:27:51

操作BOM

window

所有浏览器都支持 window 对象。它代表浏览器的窗口。

所有全局 JavaScript 对象,函数和变量自动成为 window 对象的成员。

全局变量是 window 对象的属性。

全局函数是window对象的方法。

甚至(HTML DOM 的)document 对象也是 window 对象属性:

window.document.getElementById("header");

等同于:

document.getElementById("header");

screen

window.screen 对象不带 window 前缀也可以写:

属性:

  • screen.width
  • screen.height
  • screen.availWidth
  • screen.availHeight
  • screen.colorDepth
  • screen.pixelDepth

Location

window.location 对象可用于获取当前页面地址(URL)并把浏览器重定向到新页面。

一些例子:

  • window.location.href 返回当前页面的 href (URL)
  • window.location.hostname 返回 web 主机的域名
  • window.location.pathname 返回当前页面的路径或文件名
  • window.location.protocol 返回使用的 web 协议(http: 或 https:)
  • window.location.assign 加载新文档

History

window.history 对象包含浏览器历史。

一些方法:

  • history.back() - 等同于在浏览器点击后退按钮
  • history.forward() - 等同于在浏览器中点击前进按钮

Navigator

window.navigator 对象包含有关访问者的信息。

一些例子:

  • navigator.appName
  • navigator.appCodeName
  • navigator.platform

操作表单

获取值

如果我们获得了一个 <input> 节点的引用,就可以直接调用 value 获得对应的用户输入值:

// <input type="text" id="email">
var input = document.getElementById('email');
input.value; // '用户输入的值'

这种方式可以应用于 textpasswordhidden 以及 select 。但是,对于单选框和复选框, value 属性返回的永远是HTML预设的值,而我们需要获得的实际是用户是否“勾上了”选项,所以应该用 checked 判断:

// <label><input type="radio" name="weekday" id="monday" value="1">
Monday</label>
// <label><input type="radio" name="weekday" id="tuesday" value="2">
Tuesday</label>
var mon = document.getElementById('monday');
var tue = document.getElementById('tuesday');
mon.value; // '1'
tue.value; // '2'
mon.checked; // true或者false
tue.checked; // true或者false

设置值

设置值和获取值类似,对于 textpasswordhidden 以及 select ,直接设置 value就可以:

// <input type="text" id="email">
var input = document.getElementById('email');
input.value = 'test@example.com'; // 文本框的内容已更新

对于单选框和复选框,设置 checkedtruefalse 即可。

提交表单

通过 <form> 元素的 submit() 方法提交一个表单,例如,响应一个 buttonclick 事件,在JavaScript代码中提交表单:

<!-- HTML -->
<form id="test-form">
  <input type="text" name="test">
  <button type="button" onclick="doSubmitForm()">Submit</button>
</form>
<script>
function doSubmitForm() {
  var form = document.getElementById('test-form');
  // 可以在此修改form的input...
  // 提交form:
  form.submit();
}
</script>

这种方式的缺点是扰乱了浏览器对form的正常提交。浏览器默认点击 <button type="submit"> 时提交表单,或者用户在最后一个输入框按回车键。因此,第二种方式是响应 <form> 本身的onsubmit 事件,在提交form时作修改:

<!-- HTML -->
<form id="test-form" onsubmit="return checkForm()">
  <input type="text" name="test">
  <button type="submit">Submit</button>
</form>
<script>
function checkForm() {
  var form = document.getElementById('test-form');
  // 可以在此修改form的input...
  // 继续下一步:
  return true;
}
</script>

注意要eturn true 来告诉浏览器继续提交,如果 return false ,浏览器将不会继续提交form,这种情况通常对应用户输入有误,提示用户错误信息后终止提交form