简体   繁体   English

从html选择菜单中选择的值

[英]Selected value from html select menu

I'm trying to make clicking the battle button print "You have slain" + selected option + What I have now works for the first option , but if you select a different option in the dropdown and click battle it still says Fly. 我正在尝试点击战斗按钮打印"You have slain" + selected option + What I have now works for the first option ,但如果你在下拉列表中选择一个不同的选项并点击战斗它仍然说Fly。

Fiddle 小提琴

var mon = document.getElementById('monsters');
var monster =mon.options[mon.selectedIndex].text;

$('#battle').click(function() {
    document.getElementById('dam').innerHTML = "You have hit the " + monster + " for 5 damage";
});

In your solution, you have declared the values of the selected value globally which is set only once during the document load. 在您的解决方案中,您已全局声明所选值的值,该值仅在文档加载期间设置一次。 In order to calculate the right value, you have to declare them locally during the button click. 为了计算正确的值,您必须在按钮单击期间在本地声明它们。

$('#battle').click(function() {
  var mon = document.getElementById('monsters');
  var monster =mon.options[mon.selectedIndex].text;
    document.getElementById('dam').innerHTML = "You have hit the " + monster + " for 5 damage";
});

Working example : https://jsfiddle.net/DinoMyte/4dyph8jh/5/ 工作示例: https//jsfiddle.net/DinoMyte/4dyph8jh/5/

Updated fiddle 更新了小提琴

Because you're using jQuery it could be simply : 因为你正在使用jQuery,它可能很简单:

$('#battle').click(function() {
    $('#dam').text("You have hit the " + $('#monsters option:selected').text() + " for 5 damage");
});

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM