4

私がやろうとしているのは、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>

私がシステムに求めているのは、「請求書の提出」が押されたときに隠しフィールドから取得した値を警告することです。

function alertTest(e){
//e.parentNode
window.alert(e.parentNode.getElementsByTagName("tenentID")[0]);
}

JavaScript DOM を使用して要素にアクセスしようとしています。これが少なくともある程度の意味をなすことを願っています。ページにはこれらのエントリが多数あります。

4

5 に答える 5

6

getElementsByName代わりに使用する必要がありますgetElementsByTagName

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

getElementsByTagName は、div、input などのタグに基づいて要素を選択するためのものです。

getElementsByName

getElementsByTagName

複数の div セクションがあり、非表示の入力がこれらを使用できる最初の子であることを認識する:-

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

また

e.parentNode.firstElementChild.value;

それがfirstCHildではなく、位置がわかっている場合は、使用できます

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

フィドル

于 2013-05-29T23:11:32.287 に答える
6

現代的な方法は、 を使用することquerySelectorです。

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

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]);
    }
}

http://jsfiddle.net/ExplosionPIlls/zU2Gh/1/

于 2013-05-29T23:11:12.397 に答える
0

これを試して:

function alertTest(e){
    alert(e.parentNode.getElementsByName("tenentID")[0].value);
}
于 2013-05-29T23:10:52.677 に答える
0

私は通常、隠し要素に id 属性を設定してから、 を使用しますgetElementById

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

それから私は使うことができます...

var tenentValue = document.getElementById("tenentID").value;
于 2013-05-29T23:15:26.083 に答える
0

一般に、特定の要素にアクセスする最善の方法は、ID を指定してから getElementById() を使用することです。

function alertTest(ID){
  alert(document.getElementById(ID).value);
}

名前はページ上で重複できますが、ID は一意である必要があります。

于 2013-05-29T23:16:36.577 に答える