Aus*_*ell 3 html javascript dom
我试图做的是访问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>
Run Code Online (Sandbox Code Playgroud)
我希望系统做的是在按下"提交账单"时提醒它从隐藏字段获得的值.
function alertTest(e){
//e.parentNode
window.alert(e.parentNode.getElementsByTagName("tenentID")[0]);
}
Run Code Online (Sandbox Code Playgroud)
我试图使用JavaScript DOM来访问该元素.我希望这至少在某种程度上是有道理的.页面上会有很多这样的条目.
你需要使用getElementsByName而不是getElementsByTagName
function alertTest(e){
//e.parentNode
window.alert(document.getElementsByName("tenentID")[0]);
}
Run Code Online (Sandbox Code Playgroud)
getElementsByTagName用于根据标签选择元素,例如div,input等.
意识到你可能有多个div部分,你的隐藏输入是你可以使用的第一个孩子: -
e.parentNode.getElementsByTagName("input")[0].value;
Run Code Online (Sandbox Code Playgroud)
要么
e.parentNode.firstElementChild.value;
Run Code Online (Sandbox Code Playgroud)
如果它不是第一个房子,你知道这个位置,那么你可以使用
e.parentNode.children(n).value; //n is zero indexed here
Run Code Online (Sandbox Code Playgroud)
现代方法将是使用querySelector.
e.parentNode.querySelector("[name=tenentID]");
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/ExplosionPIlls/zU2Gh/
但是,您也可以使用更多手动DOM解析来执行此操作:
var nodes = e.parentNode.getElementsByTagName("input"), x;
for (x = 0; x < nodes.length; x++) {
if (nodes[x].name === "tenentID") {
console.log(nodes[x]);
}
}
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/ExplosionPIlls/zU2Gh/1/