下拉菜单显示新信息而不重新加载页面

时间:2014-04-11 23:32:24

标签: javascript

根据下拉菜单中选择的内容,尝试在行星上显示下拉菜单显示信息。我已经使用console.log来确保我实际上从选定的选项中获取了一个值,但问题是我无法弄清楚如何在不重新加载页面的情况下显示信息。我只能让它显示第一个选项,它只是一个空的选择字符串。

的javascript

function updateMenu() {
'use strict';

// Get references to the menus:
var pag = document.getElementById('pag');
var pag2 = document.getElementById('pag2');

// For storing the options:
var options = null;

// Empty the second menu:
while (pag2.firstChild) {
    pag2.removeChild(pag2.firstChild);
}

// Determine the options:
if (pag.value == 'Planets') {
    options = ['Select', 'Earth', 'Jupiter', 'Mars', 'Mercury', 'Neptune', 'Saturn', 'Uranus', 'Venus'];
} else if (pag.value == 'Galaxies') {
    options = ['Select', 'Andromeda Galaxy', 'M82 Galaxy', 'Milky Way', 'NGC 5866', 'Omega Centauri', 'Whirlpool Galaxy'];
}

// Update the menu:
if (options) {
    pag2.disabled = false;

    // Add the options to the menu:
    for (var i = 0, count = options.length; i < count; i++) {
        var opt = document.createElement('option');
        opt.text = opt.value = options[i];
        pag2.appendChild(opt);
    }

} else { // No selection!
    pag2.disabled = true;
}

if (pag.value == 'Planets') {
    displayPlanets();
}

} // End of updateMenu() function.

function displayPlanets() {
'use strict';

var output = document.getElementById('output');
var planetInfo = [ '',
    'Earth is the third planet from the Sun, and the densest and fifth-largest of the eight planets in the Solar System. It is also the largest of the Solar System\'s four terrestrial planets. It is sometimes referred to as the world, the Blue Planet, or by its Latin name, Terra. Earth formed approximately 4.54 billion years ago, and life appeared on its surface within one billion years. Earth\'s biosphere then significantly altered the atmospheric and other basic physical conditions, which enabled the proliferation of organisms as well as the formation of the ozone layer, which together with Earth\'s magnetic field blocked harmful solar radiation, and permitted formerly ocean-confined life to move safely to land.',
    'Jupiter is the fifth planet from the Sun and the largest planet in the Solar System. It is a gas giant with mass one-thousandth that of the Sun but is two and a half times the mass of all the other planets in our Solar System combined. Jupiter is classified as a gas giant along with Saturn, Uranus and Neptune. Together, these four planets are sometimes referred to as the Jovian or outer planets. The planet was known by astronomers of ancient times, and was associated with the mythology and religious beliefs of many cultures. The Romans named the planet after the Roman god Jupiter. When viewed from Earth, Jupiter can reach an apparent magnitude of -2.94, making it on average the third-brightest object in the night sky after the Moon and Venus. (Mars can briefly match Jupiter\'s brightness at certain points in its orbit.)',
    'Mars is the fourth planet from the Sun and the second smallest planet in the Solar System. Named after the Roman god of war, it is often described as the "Red Planet", as the iron oxide prevalent on its surface gives it a reddish appearance. Mars is a terrestrial planet with a thin atmosphere, having surface features reminiscent both of the impact craters of the Moon and the volcanoes, valleys, deserts, and polar ice caps of Earth. The rotational period and seasonal cycles of Mars are likewise similar to those of Earth, as is the tilt that produces the seasons. Mars is the site of Olympus Mons, the second highest known mountain within the Solar System, and of Valles Marineris, one of the largest canyons. The smooth Borealis basin in the northern hemisphere covers 40% of the planet and may be a giant impact feature. Mars has two moons, Phobos and Deimos, which are small and irregularly shaped. These may be captured asteroids, similar to 5261 Eureka, a Martian trojan asteroid.',
    'Mercury is the innermost planet in the Solar System. It is also the smallest, and its orbit is the most eccentric (that is, the least perfectly circular) of the eight planets. It orbits the Sun once in about 88 Earth days, completing three rotations about its axis for every two orbits. The planet is named after the Roman god Mercury, the messenger to the gods. Mercury\'s surface is heavily cratered and similar in appearance to Earth\'s Moon, indicating that it has been geologically inactive for billions of years. Due to its near lack of an atmosphere to retain heat, Mercury\'s surface experiences the steepest temperature gradient of all the planets, ranging from a very cold 100 K at night to a very hot 700 K during the day. Mercury\'s axis has the smallest tilt of any of the Solar System\'s planets, but Mercury\'s orbital eccentricity is the largest. The seasons on the planet\'s surface are caused by the variation of its distance from the Sun rather than by the axial tilt, which is the main cause of seasons on Earth and other planets. At perihelion, the intensity of sunlight on Mercury\'s surface is more than twice the intensity at aphelion.',
    'Neptune is the eighth and farthest planet from the Sun in the Solar System. It is the fourth-largest planet by diameter and the third-largest by mass. Neptune is 17 times the mass of Earth and is somewhat more massive than its near-twin Uranus, which is 15 times the mass of Earth but not as dense.[12] On average, Neptune orbits the Sun at a distance of 30.1 AU, approximately 30 times the Earth–Sun distance. Named for the Roman god of the sea. Neptune was the first planet found by mathematical prediction rather than by empirical observation. Unexpected changes in the orbit of Uranus led Alexis Bouvard to deduce that its orbit was subject to gravitational perturbation by an unknown planet. Neptune was subsequently observed on 23 September 1846 by Johann Galle within a degree of the position predicted by Urbain Le Verrier, and its largest moon, Triton, was discovered shortly thereafter, though none of the planet\'s remaining 12 moons were located telescopically until the 20th century. Neptune has been visited by only one spacecraft, Voyager 2, which flew by the planet on 25 August 1989.',
    'Saturn is the sixth planet from the Sun and the second largest planet in the Solar System, after Jupiter. Named after the Roman god Saturn, its astronomical symbol represents the god\'s sickle. Saturn is a gas giant with an average radius about nine times that of Earth. While only one-eighth the average density of Earth, with its larger volume Saturn is just over 95 times as massive as Earth. Saturn\'s interior is probably composed of a core of iron, nickel and rock (silicon and oxygen compounds), surrounded by a deep layer of metallic hydrogen, an intermediate layer of liquid hydrogen and liquid helium and an outer gaseous layer. The planet exhibits a pale yellow hue due to ammonia crystals in its upper atmosphere. Electrical current within the metallic hydrogen layer is thought to give rise to Saturn\'s planetary magnetic field, which is slightly weaker than Earth\'s and around one-twentieth the strength of Jupiter\'s. The outer atmosphere is generally bland and lacking in contrast, although long-lived features can appear. Wind speeds on Saturn can reach 1,800 km/h (1,100 mph), faster than on Jupiter, but not as fast as those on Neptune.',
    'Uranus is the seventh planet from the Sun. It has the third-largest planetary radius and fourth-largest planetary mass in the Solar System. It is named after the ancient Greek deity of the sky Uranus, the father of Cronus (Saturn) and grandfather of Zeus (Jupiter). Though it is visible to the naked eye like the five classical planets, it was never recognized as a planet by ancient observers because of its dimness and slow orbit. Sir William Herschel announced its discovery on March 13, 1781, expanding the known boundaries of the Solar System for the first time in modern history. Uranus was also the first planet discovered with a telescope. Uranus is similar in composition to Neptune, and both are of different chemical composition than the larger gas giants Jupiter and Saturn. Astronomers sometimes place them in a separate category called "ice giants". Uranus\'s atmosphere, while similar to Jupiter\'s and Saturn\'s in its primary composition of hydrogen and helium, contains more "ices" such as water, ammonia, and methane, along with traces of hydrocarbons.',
    'Venus is the second planet from the Sun, orbiting it every 224.7 Earth days. The planet is named after the Roman goddess of love and beauty. After the Moon, it is the brightest natural object in the night sky, reaching an apparent magnitude of -4.6, bright enough to cast shadows. Because Venus is an inferior planet from Earth, it never appears to venture far from the Sun: its elongation reaches a maximum of 47.8 degrees. Venus reaches its maximum brightness shortly before sunrise or shortly after sunset, for which reason it has been referred to by ancient cultures as the Morning Star or Evening Star. Venus is classified as a terrestrial planet and is sometimes called Earth\'s "sister planet" owing to their similar size, gravity, and bulk composition (Venus is both the closest planet to Earth and the planet closest in size to Earth). However, it has been shown to be very different from Earth in other respects. Venus is shrouded by an opaque layer of highly reflective clouds of sulfuric acid, preventing its surface from being seen from space in visible light. It has the densest atmosphere of the four terrestrial planets, consisting mostly of carbon dioxide.'
];
planetInfo = planetInfo[pag2.selectedIndex];
if (output.textContent !== undefined) {
    output.textContent = planetInfo;
} else {
    output.innerHTML = planetInfo;
}

return false;
}

// Establish functionality on window load:
window.onload = function() {
'use strict';

// Get the select menu:
var pag = document.getElementById('pag');
var output = document.getElementById('output');

// Clear out the existing options:
while (pag.firstChild) {
    pag.removeChild(pag.firstChild);
}

// Add the new options:
var options = ['Select', 'Planets', 'Galaxies'];
for (var i = 0, count = options.length; i < count; i++) {
    var opt = document.createElement('option');
    opt.text = opt.value = options[i];
    pag.appendChild(opt);
}

// Add an event handler:
pag.onchange = updateMenu;

// Create the other select menu:
var pag2 = document.createElement('select');
pag2.id = 'pag2';
pag2.disabled = true;
pag.parentNode.appendChild(pag2); 


};

1 个答案:

答案 0 :(得分:0)

更改选择元素选项的最佳方法是更改 innerHTML 属性

pag.innerHTML = ' <option>Hello</option> <option>World!</option> ';

要在另一个选择元素的所选值更改时使用onchange事件执行此操作(就像您在代码中所做的那样)。


我的解决方案(Fiddle):


首先,声明一些变量..

var pag = document.getElementById('pag');
var pag2 = document.getElementById('pag2');
var output = document.getElementById('output');
pag.onchange = updateMenu;
pag2.onchange = displayPlanets;

这里没什么特别的,继续好东西

function updateMenu() {
    // Decide on options
    if (pag.value == 'Select')
        pag2.innerHTML = '';
    if (pag.value == 'Planets')
        pag2.innerHTML = '<option>' + Planets.join('</option><option>') + '</option>';
    if (pag.value == 'Galaxies')
        pag2.innerHTML = '<option>' + Galaxies.join('</option><option>') + '</option>';

    // Disable || Enable
    pag2.disabled = (pag.value == 'Select');
}

function displayPlanets() {
    // Display Planet Info
    if (pag.value == 'Planets')
        output.innerHTML = planetInfo[pag2.selectedIndex];
}

updateMenu上有3个if来检查第一个选择中所选值的内容。 在此基础上,决定将哪一组选项赋予第二个select,并使用innerHTML属性插入这些选项。


* 旁注: 我希望您熟悉数组的join方法,如果没有,请告诉我,我会解释它是如何工作的


此外,根据所选选项是否为select选项启用或禁用第二个"Select"


displayPlanets功能附加到第二个select的{​​{1}}事件,因此当其值更改时,会验证onchange选项是否为"Planets"在第一个select上选择,如果是,则显示正确的行星信息。


希望澄清它;)