从HTML选择菜单中选定的值

3
我试图使点击战斗按钮打印"You have slain" + 选择的选项 + 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";
});

你应该使用更多的jQuery -> https://jsfiddle.net/4dyph8jh/9/ - adeneo
2个回答

6

在您的解决方案中,您已经全局声明了所选值的值,这些值仅在文档加载时设置一次。为了计算正确的值,您必须在按钮单击时将它们声明为本地变量。

$('#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";
});

示例: https://jsfiddle.net/DinoMyte/4dyph8jh/5/

这是一个工作示例,可以参考链接中的代码。

总是那些简单的事情让我无法理解。谢谢。 - Shniper
没关系,每个人都会偶尔错过一些事情。祝你有美好的一天!! - DinoMyte
另一双眼睛总是有帮助的。能够避免你花费数小时的时间寻找,然后才发现“啊……”顺便说一句,这是一个有趣的问题。 - Shockwave

1

更新的代码片段

因为您正在使用jQuery,所以可以简单地实现:

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

希望这有所帮助。

看到另一个简单的错误,在你更新之前,我尝试过$('#battle').click(function() { $('#dam').text("You have hit the " + $('#monsters>option:selected').text() + " for 5 damage"); });但是它没有起作用哈哈。 - Shniper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接