我如何显示名称“第一个文本框名称”,我已经尝试了很多方法,但似乎没有任何效果。
这是其他文本框中的文本框。
<td>FirstTextbox Name:
<input id="box1" name="box1" class="nosonly" type="text" oninput="calculate()" /></td>
</td>
<script>
var x = document.getElementById("box1").WhatwouldGohere?
alert(x);
</script>
最佳答案
文本框没有结束标记,因此不能有任何 innerHTML
.
但是,您可以访问文本框的其他方面。另外,请勿使用内联 HTML 事件属性( onclick
、 onmousover
等)。尽管你看到它们随处可见,但这只是因为许多 JavaScript 新人养成了坏习惯。有many reasons 不要使用它们。
// Get a reference to the textbox
var tb = document.getElementById("box1");
// Set up the event handler in JavaScript, not HTML
tb.addEventListener("input", calculate);
function calculate(){
// You can access HTML attributes as object properties:
console.clear();
// To get the content of the parent element, use the parentElement property
// Then, access the textContent of that element to only get text (and not
// nested child elements). Finally, strip off any leading or trailing
// spaces from that value (if desired) with .trim()
var parentText = this.parentElement.childNodes[0].textContent.trim();
alert("The text that preceeds the textbox is: " + parentText);
console.log("The name of the textbox is: " + box1.name);
console.log("There are " + this.value.length + " characters in the box.");
console.log("The value of the box is: " + this.value);
}
<td>FirstTextbox Name:
<input id="box1" name="box1" class="nosonly" type="text">
</td>
但是,您的问题询问了文本框的“标签”,结果发现实际上有一个 <label>
元素,您可以并且应该使用它,因为它创建了更易于访问的 UI,并使操作变得更加容易:
// Get a reference to the textbox and the label
var tb = document.getElementById("box1");
var lbl = document.querySelector("label[for=box1]");
// Set up the event handler in JavaScript, not HTML
tb.addEventListener("input", calculate);
function calculate(){
// You can access HTML attributes as object properties:
console.clear();
alert("The text that preceeds the textbox is: " + lbl.textContent);
console.log("The name of the textbox is: " + box1.name);
console.log("There are " + this.value.length + " characters in the box.");
console.log("The value of the box is: " + this.value);
}
<td>
<label for="box1">FirstTextbox Name:</label>
<input id="box1" name="box1" class="nosonly" type="text">
</td>
关于javascript - 显示带有警报的文本框名称的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46185377/