2014-04-11 2 views
0

드롭 다운 메뉴에서 선택한 항목에 따라 행성에 드롭 메뉴 정보를 표시하려고했습니다. console.log를 사용하여 실제로 선택한 옵션에서 값을 다시 얻었는지 확인했지만 문제는 페이지를 다시로드하지 않고 정보를 표시하는 방법을 파악할 수 없다는 것입니다. 난 단지 빈 선택 문자열입니다 첫 번째 옵션을 표시 얻을 수 있습니다. 또 다른 선택 요소의 선택 값이 변경 될 때페이지를 새로 고침하지 않고 드롭 다운 메뉴를 새로 고침

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

이 작업을 수행하려면 :

자바 스크립트

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


}; 
+0

왜) '여기에 값'경우 (SelectNode.value === 테스트 {/ * 할 물건 * /}'은'onchange' 이벤트를 사용하지 ? 실제로'select '와'options' 모두를 HTML의 Strings로 분리하고'Element'를 사용하여 추가 할 것입니다.innerHTML = ""입니다. – PHPglue

답변

0

select 요소의 옵션을 변경하는 가장 좋은 방법은 innerHTML재산을 변경하는 것입니다 코드에서와 마찬가지로 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 함수이므로 그 값이 변경 될 때, 제 selectonchange 이벤트에 부착되고 그것 "Planets" 옵션 제 select을 선택하고, 만약 그렇다면, 적절한 표시 여부 확인 행성 정보. 그것을 명확히


희망)

+0

대단히 감사합니다 !! 잠시 휴식을 취한 후 바로 지금 한 가지 질문 만하십시오. 배열 변수를 전역 변수로 만들지 아니면 window.onload 함수로 만들어야하나요? – HeyZeusV

+0

세계 곳곳에서 선언 할 수있는 더 많은 장소에서 필요하다면. 하지만 당신이 페이지에서 js 콘솔을 혼란스럽게하고 싶은 사람으로부터이 변수들을 숨기 때문에 window.onload에 그것들이 필요하다면 그것도 좋습니다. – ThatWeirdo

+0

몇 가지 이유로 출력에 대한 가치를 얻을 수 없습니다. 그것은 단지 정의되지 않는다고 말합니다. 그것은 바이올린에서 작동하지 않지만 출력을 표시하는 것 이외에 파이어 폭스를 시도 할 때 작동하지 않습니다. [피들] (http://jsfiddle.net/cYRd7/5/) – HeyZeusV

관련 문제