JavaScript + HTML simple implementation of string reversal page

Because pure HTML is difficult to implement some flow control level operations, such as variables, loops, and the introduction of JavaScript, it can be more convenient to write interactive

DOM extraction object

Using specific APIs, you can extract label objects, and these objects need to have some attributes, such as text input boxes, value is the input value, and introducing variables into a convenience language can achieve more complex functions

Let's take a look at the way to get the label object

 		document.getElementById
        document.getElementsByClassName
        document.getElementsByName
        document.querySelector
// 通过id来获得对象,id唯一
var obj = document.getElementById();

// 通过class名获得对象,注意是获得一群
var obj = document.getElementsByClassName();

// 通过name来获得对象,获得一群,Element加不加s以和getElementById区分
var obj = document.getElementsByName();

// 通过标签名字来获取第一个标签
var obj = document.querySelector();

example

Because there are fewer objects, getElementsById is used. It is worth noting that the input of the text box, whether it is input or textarea label, is value, notinnerText
Insert picture description here

<!DOCTYPE html>
<html>
<head>
	<title>javascript test</title>
</head>
<body>
    <div>
        输入一行<br />
        <textarea id="in1" name="in1" class="in1"></textarea>
    </div>
	<div>
        <button id="btn">点我转换</button>
        <button id="clr">点我清空</button>
    </div>	
	<div>
        反转后的字符串<br />
		<textarea id="ou1"></textarea>
	</div>
	<script type="text/javascript">
        // 获取各个标签对象
        var btn = document.getElementById('btn');   // 点我转换
        var clr = document.getElementById('clr');   // 点我清空
        var in1 = document.getElementById('in1');   // 输入框
        var ou1 = document.getElementById('ou1');   // 输出框
        // 反转字符串函数
		function reverse(s) {
		    return s.split("").reverse().join("");
		}
        // 配置‘点我反转’按钮回调函数
		btn.onclick = function () {
		    var s = in1.value;
		    ou1.innerText = reverse(s);
		}
		// 清空
		clr.onclick = function () {
		    in1.value = null;
		    ou1.innerText = null;
		}
	</script>
</body>
</html>
Published 262 original articles · won 11 · 10 thousand views

Guess you like

Origin blog.csdn.net/weixin_44176696/article/details/105524508