触发功能后停止刷新页面

时间:2011-12-20 12:08:11

标签: javascript html drop-down-menu

我的任务是构建一个非常简单的应用程序,其中包含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);
}

我是否比实际需要更困难?!

3 个答案:

答案 0 :(得分:3)

那是因为document.write在显示内容之前清除了页面。你永远不需要使用那个功能。

相反,您可以将其附加到例如身体:

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

答案 1 :(得分:1)

您是否注意到您的JS函数被调用tryThis()并且在您调用的事件处理程序tryThsis()

但是在你的情况下我不会使用document.write,好的替代方案会附加到身体或有DIV并更改DIV的innerHTML

答案 2 :(得分:0)

首先在表单上添加一个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操作,它将替换当前页面的整个正文内容。