簡體   English   中英

如何在同一瀏覽器窗口中從另一表單中的一個表單訪問變量?

[英]How can I access a variable from one Form in a different Form inside the same browser window?

我無法從公司使用的基於Web的系統中的特定表單中獲取字符串的值。

在瀏覽器中打開時,它包含三個表單(非框架)。 我正在構建的表單中有一個較薄的左側Menu窗體,一個較薄的頂部水平Banner窗體以及其余右下80%的內容。

我需要能夠從名為“ mainForm”的頂部橫幅表單中獲取一個字符串。

該字符串是動態填充的,因為未設置,它只是出現在TD標簽之間。 同樣,它所駐留的TD元素沒有id或名稱,但是它是類“ userName”的唯一實例。

我嘗試了幾種排列方式來嘗試訪問此類/字符串組合。

我嘗試過的例子:

    document.getElementsByClassName("userName")
    document.querySelector('form[name="mainForm"] .userName').innterHTML
    document.getElementsByClassName("userName")[0].innerText
    document.mainForm.querySelector('.userName').innerText
    document.forms.mainForm.getElementsByClassName('userName')
    mainForm.getElementsByClassName("userName")
    window.form["mainForm"].getElementsByClassName("userName")
    document.form["mainForm"].getElementsByClassName("userName")
    window.parent.document.getElementsByClassName("userName")
<!--Excerpts of code-->

    <form name="mainForm" style="margin: 0px;" action="">
        <table>
            <tr>
            <td align="right" class="userName" nowrap="">Target Text</td>
            </tr>
        </table>
    </form>

    <form id="myForm" method="post" action="">
        <button type="button" id="btnLog" name="btnLog" onclick="getLog()">Get 
        Log</button>
    </form>

    function getLog() {
        var elementLog = document.getElementsByClassName("userName");
        var log = elementLog.textContent;
        alert(log);
    }

我希望alert(log)返回userName類的字符串值。

實際發生的情況是警報觸發並顯示“未定義”或控制台錯誤,導致無法獲取未定義或空引用的屬性。

我相信您在尋找的是innerHTML (而不是innterHTML ):

 function getLog() { var elementLog = document.getElementsByClassName("userName")[0]; var log = elementLog.innerHTML; console.log(log); } 
 <!--Excerpts of code--> <form name="mainForm" style="margin: 0px;" action=""> <table> <tr> <td align="right" class="userName" nowrap="">Target Text</td> </tr> </table> </form> <form id="myForm" method="post" action=""> <button type="button" id="btnLog" name="btnLog" onclick="getLog()">Get Log</button> </form> 

    function getLog() {
        alert(document.getElementsByClassName("userName").item(0).innerText);
        }

似乎已經解決了問題!

[0]替換.item(0)相同

將javascript函數放在<head></head>標記之間或通常在調用它們之前也很重要!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM