Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用javascript访问隐藏的输入_Javascript_Html_Dom - Fatal编程技术网

如何使用javascript访问隐藏的输入

如何使用javascript访问隐藏的输入,javascript,html,dom,Javascript,Html,Dom,我试图做的是访问div中的隐藏对象。发生的是用户将单击按钮,然后执行一些任务,例如删除用户。如果我展示我所拥有的,这可能会更容易 <div class="mgLine"> <input type="hidden" name="tenentID" value="1"> <p class="mgName">James Gear</p> <input type="text" class="mgBill" value="" p

我试图做的是访问div中的隐藏对象。发生的是用户将单击按钮,然后执行一些任务,例如删除用户。如果我展示我所拥有的,这可能会更容易

<div class="mgLine">
    <input type="hidden" name="tenentID" value="1">
    <p class="mgName">James Gear</p>
    <input type="text" class="mgBill" value="" placeholder="Post Bill Link Here">
    <a href="#" class="mgButton" onclick="alertTest(this)">Submit Bill</a>
    <a href="#" class="mgNP">Not Paid</a>
    <a href="#" class="mgButton">Change Password</a>
    <a href="#" class="mgButton">Delete User</a>
</div>
我正在尝试使用JavaScript DOM访问元素。我希望这至少有点道理。页面上会有许多这样的条目。

试试这个:

function alertTest(e){
    alert(e.parentNode.getElementsByName("tenentID")[0].value);
}

现代的方法是使用
querySelector

e.parentNode.querySelector("[name=tenentID]");

但是,您也可以通过一些更为手动的DOM解析来完成:

var nodes = e.parentNode.getElementsByTagName("input"), x;
for (x = 0; x < nodes.length; x++) {
    if (nodes[x].name === "tenentID") {
        console.log(nodes[x]);
    }
}
var nodes=e.parentNode.getElementsByTagName(“输入”),x;
对于(x=0;x

您需要使用
getElementsByName
而不是
getElementsByTagName

function alertTest(e){
//e.parentNode
window.alert(document.getElementsByName("tenentID")[0]);
}
getElementsByTagName用于根据标记选择元素,如div、input等

意识到您可能有多个div部分,并且您的隐藏输入是您可以使用的第一个子项:-

e.parentNode.getElementsByTagName("input")[0].value;

如果它不是第一个孩子,并且你知道这个位置,那么你可以使用

e.parentNode.children(n).value; //n is zero indexed here

我通常在隐藏元素上设置一个id属性,然后使用
getElementById

<input type="hidden" id="tenentID" name="tenentID" value="1">

通常,访问特定元素的最佳方法是给它一个ID,然后使用getElementById()


名称可以在页面上重复,但ID必须是唯一的。

使用getElementsByName而不是GetElementsByTagname始终是第一个子项吗?如果是这样,
e.parentNode.children[0]
如果有几个呢?这里似乎是这样。当我研究这个问题时,我得到了一个错误:
Object#没有方法“getElementsByName”
(我使用的代码与您的相同)。但是,
document.getElementsByName(“tenentID”)[0]
起作用了。这看起来对我正在尝试的工作很有效。非常感谢你的帮助和其他人的帮助!
e.parentNode.children(n).value; //n is zero indexed here
<input type="hidden" id="tenentID" name="tenentID" value="1">
var tenentValue = document.getElementById("tenentID").value;
function alertTest(ID){
  alert(document.getElementById(ID).value);
}