javascript - 显示带有警报的文本框名称的语法

标签 javascript

我如何显示名称“第一个文本框名称”,我已经尝试了很多方法,但似乎没有任何效果。

这是其他文本框中的文本框。

<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 事件属性( onclickonmousover 等)。尽管你看到它们随处可见,但这只是因为许多 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/

相关文章:

javascript - 如何锁定页面上的 JavaScript 元素?

javascript - jQuery AJAX 和 JSON 性能查询

javascript - jquery 和 json 数组

php - 禁用 Ajax/http 成功消息?

javascript - api google maps javascript v3 中的 InfoWindow

javascript - 如何制作多模态(使用纯 css)以定位唯一 ID?

javascript - 如何在 CRM Online 2013 中拥有唯一的 ID 号

返回函数的 Javascript 作用域错误函数

javascript - 检查是在服务器上运行还是在本地运行

javascript - 如何将 PHP 循环转换为 JSON 循环?