1. js入门基础-html元素属性操作
简介:
html 元素标签:
p(段落) 、 input(输入)、 a(链接)等
属性:
<input id="text1" type="text"/> 对于input标签 类型为text 文本输入框,id 就是它的属性, text1 就是对应的值。
操作:
读、写(修改、替换)
案例:
一: 弹出按钮对应的名字
<html>
<head>
<script>
window.onload = function(){
var obtn1 = document.getElementById("btn1");
obtn1.onclick = function(){
alert(obtn1.value);
}
}
</script>
</head>
<body>
<input type="button" id="btn1" value="hello"/>
</body>
</html>
效果:
原理:html上新增 <input>标签类型为 button 按钮。值value 为 hello 。当浏览器加载(渲染)完 该页面 window.onload 就是执行匿名函数 function() 该函数内部 调用 getelementbyId 输入input 的id名 则就可得到该对象obtn。 当点击该按钮时候希望获取按钮值 则写点击函数:onclick。 内部通过alert 进行弹窗。对应的值内容为 obtn.value 就是input 里面的value="hello"。
二、替换点击按钮 替换、修改文本输入框中的值
<html>
<head>
<script>
window.onload = function(){
var obtn1 = document.getElementById("btn1");
var otext = document.getElementById("text1");
obtn1.onclick = function(){
otext.value = obtn1.value;
}
}
</script>
</head>
<body>
<input type="text" id = "text1"/>
<input type="button" id="btn1" value="hello"/>
</body>
</html>
效果:
原理:文本框 otext.value 的值 赋值为 obtn的value值
三、字符串连接 (修改)
直接赋值形式 otext.value = obtn.value 相当于替换。要想链接我们自己的值则 通过 + 号 形如 '你好' +'明天'
obtn1.onclick = function(){
otext.value = obtn1.value + 'world';
}
效果:
四、内容的获取
从上面的案例中可以知道 标签属性的获取方式 ,该属性都是再标签同一行的。此时如果想获取到标签内部值则可以直接调用innerHTML (inner:内部):值得注意的是,该方法会将用户的值当成html 语法
4.1 获取标签内容
<html>
<head>
<script>
window.onload = function(){
var obtn1 = document.getElementById("btn1");
var otext = document.getElementById("text1");
var ocon = document.getElementById("content");
obtn1.onclick = function(){
otext.value = ocon.innerHTML;
}
}
</script>
</head>
<body>
<input type="text" id = "text1"/>
<input type="button" id="btn1" value="hello"/>
<p id="content" >
hello the world!!!
</p>
</body>
</html>
效果:
4.2 插入标签值
<html>
<head>
<script>
window.onload = function(){
var obtn1 = document.getElementById("btn1");
var otext = document.getElementById("text1");
var ocon = document.getElementById("content");
obtn1.onclick = function(){
ocon.innerHTML = otext.value;
}
}
</script>
</head>
<body>
<input type="text" id = "text1"/>
<input type="button" id="btn1" value="hello"/>
<p id="content" >
hello the world!!!
</p>
</body>
</html>
效果: