我如何使用警告框检索此值?

How can i retrieve this value using an alert box?

在我的网站上,我有一个具有以下配置的 html 文件:

<script>
window.Conf.page = window.Conf.page || {};
    
$.extend(Conf.page, {"newNotifications":false,"userId":"125"}
</script>

在同一页面中,我需要使用脚本检索 userId 的值并将其显示到警告框中。我尝试使用这个脚本:

<script>
alert(document.getElementsByName('userId'))
</script>

但是我 [object NodeList] 进入警告框。

我可以使用什么代码来获取警告框中的 userId 值?

这样试试:

alert(window.Conf.page.userId);
<script>
  window.Conf.page = window.Conf.page || {}; 
  var json = $.extend(Conf.page, {"newNotifications":false,"userId":"125"});

  alert(json.userId);
</script>

<script>
  window.Conf.page = window.Conf.page || {}; 
  Conf.page = $.extend(Conf.page, {"newNotifications":false,"userId":"125"});

  alert(Conf.page.userId);
</script>

这里获取的是节点列表中元素的值属性,节点列表是所有名称为属性的节点与你传入的匹配的列表,在off有可能你有两个名称为 属性 的输入字段相同,它们的索引分别为 0 和 1。

document.getElementsByName('userId')[0].value

我认为如果要查找 HTML 标签,您正在寻找的是 getElementById,或者在您的情况下,只需 window.Conf.page.userId 即可获取值。

window.pageConf = window.pageConf || {};
$.extend(pageConf, {"newNotifications":false,"userId":"125"});

function onTestClick() {
  var a = document.getElementsByName('userId');
  document.getElementById('myLabelId').innerText = a.length;
  // Result: 0

  document.getElementById('myLabelId').innerText += " " + window.pageConf.userId;
  // Result: 125
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="onTestClick()">Test</button><br/><br/>
<label id="myLabelId"></label>

说了这么多,还是说说标签中的“名字”吧

getElementsByName returns 一个数组,因为名称对于一个元素来说不是唯一的。名称主要用于两件事:

  1. 对于回发:提交表单时,输入的值与标签中的“名称”一起发布。例如:

Comments: <input id='myUniqueLocalId' name='comments' />

  1. 将单选按钮或复选框组合在一起。小例子:

function onTestClick() {
  var q1 = document.getElementsByName('q1');
  
  document.getElementById('myLabelId').innerText += " " + q1.length + " " + q1[0].value + " " + q1[1].value;
  // Result: 2 Yes No
}
Question 1: 
<input type="radio" id="Yes" name="q1" value="Yes" checked>
<label for="Yes">Yes</label><be>
<input type="radio" id="No" name="q1" value="No">
<label for="No">No</label><br>

Question 2:
<input type="radio" id="Yes" name="q2" value="Yes">
<label for="Yes">Yes</label><be>
<input type="radio" id="No" name="q2" value="No" checked>
<label for="No">No</label><br>

<button onclick="onTestClick()">Test</button><br/><br/>

<label id="myLabelId"></label>