簡體   English   中英

觸發功能后停止刷新頁面

[英]Stop a page from refreshing after firing a function

我的任務是構建一個非常簡單的應用程序,該應用程序在2行中有一系列下拉菜單,當選擇2時,一個簡單的函數將2個值連接起來,並在它們旁邊提供輸出,如下所示:

dropdown1 dropdown2 Output

我想要得到的是,一旦選擇了第二個下拉值,該函數就會運行並在顯示輸出的地方顯示output 但是目前看來,發生的是輸出顯示在新窗口中。

這是我到目前為止(HTML)的內容:

<form>
<select id="test">
<option>Arena/Quantum Barcelona LTBC</option>
<option>Arena/Quantum Spain LTES</option>
</select>

<select id="name" onchange="tryThis()">
<option>Name</option>
<option>Name1</option>
</select>

</form>

JavaScript的:

function tryThis() {

var string, string1 = '';

var e = document.getElementById("test");
string = e.options[e.selectedIndex].text;

var a = document.getElementById("name");
string1 = a.options[a.selectedIndex].text;
document.write(string+'_'+string1);
}

我使這變得比它需要的困難嗎?

這是因為document.write在顯示內容之前會清除頁面。 您永遠不需要使用該功能。

相反,您可以將其附加到例如body:

document.body.appendChild(
    document.createTextNode(string + '_' + string2)
);

您是否注意到您的JS函數稱為tryThis()並且在事件處理程序上您正在調用tryThsis()

但是,在您的情況下,我將避免使用document.write ,好的替代方法是附加到主體上或具有DIV並更改該DIV的innerHTML

首先在表單上放置一個ID,以便於訪問。

var a = (function () {
    var myForm = document.getElementById("myForm"),
        magic = function () {
            var a = myForm.getElementsByTagName("select"),
                b,
                c = [];
            for (b = a.length - 1; b > -1; b -= 1) {
                c.push(a[b].value);
            }
            alert(c.join(" ") + " output");
        };
    myForm.onclick = magic;
}());

您不確定特定的“輸出”應該是什么還是要如何返回數據,但是您可以開始。 除了使用警報之外,您還可以將結果推送到其他表單元素的值中。 不要使用document.write因為這不能被推遲。 如果您嘗試推遲document.write操作,它將替換當前頁面的整個正文內容。

暫無
暫無

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

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