从目标对象到script函数的调用:
Js引擎会根据字符串值,搜索上下文,获取指定类型名字的目标对象,对目标对象执行函数。
当然οnclick=message()也是可以调用的(js函数是非字符串形式)。
<input type="button"value="View message" οnclick="message()">
也可以从script函数获取目标对象的属性和方法:
从 JavaScript 访问某个 HTML 元素(目标对象),通过ID,标签名查询到目标对象
,参数也是字符串。
通过 id 找到 HTML 元素
通过标签名找到 HTML 元素
通过类名找到 HTML 元素
varx=document.getElementById("intro");
varx=document.getElementById("main");
vary=x.getElementsByTagName("p");
提示:通过类名查找 HTML 元素在 IE 5,6,7,8 中无效。
实例:
function myFunction()
{
document.getElementById("demo").innerHTML="HelloWorld";
document.getElementById("myDIV").innerHTML="Howare you?";
}
<h1 id="id1">My Heading1</h1>
<button type="button"οnclick="document.getElementById('id1').style.color='red'"> //要用’red’
点击这里
</button>
对象的访问this及this下的遍历
This可以指代当前的控件,遍历一个对象可以遍历到对象的属性(故可以直接使用属性)。
<html>
<head>
<scripttype="text/javascript">
functionvalidate_required(field,alerttxt)
{
with(field)
{
if (value==null||field.value=="")// value可以用field.value代替,对象下面的属性都可以找到
{alert(alerttxt);return false}
else {return true}
}
}
functionvalidate_form(thisform)
{
with(thisform) // thisform就是表单对象
{
if (validate_required(email,"Email must be filled out!")==false) // email可以用thisform.email代替,"email"不行
{thisform.email.focus();return false}
}
}
</script>
</head>
<body>
<formaction="submitpage.htm" οnsubmit="return validate_form(this)"method="post">
Email:<input type="text" name="email" size="30">
<inputtype="submit" value="Submit">
</form>
</body>
</html>