在.aspx页面上使用JavaScript设置标签文本

时间:2017-01-05 17:48:57

标签: javascript html asp.net

我已将此JavaScript代码放在JavaScript.js文件中:

var target = Number(prompt("Enter The New Number"));
function monthName(){
    var month = target == 1 ? month = "January" : target == 2 ? month = "February" : target == 3 ? month = "March" : target == 4 ? "April" : target == 5 ? "May" : target == 6 ? "June" : target == 7 ? "July" : target == 8 ? "August" : target == 9 ? "September" : target == 10 ? "October" : target == 11 ? "November" : target == 12 ? "December" : "Unknown Month";
    return month;
}
document.getElementById('yes').html= monthName();

并添加了一个带有此特定ID的标签。

<label id="yes" ></label>

2 个答案:

答案 0 :(得分:3)

  1. 输入检查号码
  2. 如果可接受的输入,则使用数组
  3. 分配给innerHTML(区分大小写)
  4. 功能只能在DOM
  5. 中存在标签后运行
  6. 注意未来JS月份为0(此处不相关)
  7. id                    int64
    chain                 int64
    dept                  int64
    category              int64
    company               int64
    dtype: object
    
    function monthName(month) {
      month = month.trim();
      if (isNaN(month) || month == "" || month < 0 || month > 12) return "unknown";
      return ["unknown", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][month];
    }
    // this needs to be after the label exists or wrapped in 
    // window.onload=function() {...} or similar 
    document.getElementById('yes').innerHTML = monthName(prompt("Enter The New Number", ""));

答案 1 :(得分:1)

正如@epascarello指出的那样,使用.innerHTML代替.html

  

Element.innerHTML属性设置或获取描述元素后代的HTML语法。

阅读Element.innerHTML - Web APIs | MDN

工作代码段

document.addEventListener("DOMContentLoaded", function(event) {

  var target = Number(prompt("Enter The New Number"));

  function monthName() {
    var month = target == 1 ? month = "January" : target == 2 ? month = "February" : target == 3 ? month = "March" : target == 4 ? "April" : target == 5 ? "May" : target == 6 ? "June" : target == 7 ? "July" : target == 8 ? "August" : target == 9 ? "September" : target == 10 ? "October" : target == 11 ? "November" : target == 12 ? "December" : "Unknown Month";
    return month;
  }

  document.getElementById('yes').innerHTML = monthName();

});
<label id="yes"></label>

在回复您的评论时,将您现有的JavaScript代码添加到DOMContentLoaded的事件监听器中并修复.innerHTML,以确保在加载DOM内容后执行该代码。确保在DOMContentLoaded事件处理程序中使用@ mplungjan的JavaScript代码,因为它编写得很好并且比我的更好。