这是我的codepen:
http://codepen.io/ekilja01/full/KaMXjp/
我正在尝试检测选择了哪个单选按钮,然后显示适当的输出,无论是摄氏度还是华氏度作为最终输出。
这是我的HTML:
<body>
<div class="container-fluid">
<i class="fa fa-thermometer-empty fa-2x" aria-hidden="true"></i>
<br><br><br>
<form>
<input type="radio" name="celsiusOrFahrenheit" value="f" id="fahrenheit"> Fahrenheit °F;<br>
<input type="radio" name="celsiusOrFahrenheit" value="c" id ="celsius" > Celsius °C<br>
</form>
<div class="yourlocation">
<h1>Your location is: </h1>
<p class="yourLocationGoesHere">
</p>
</div>
<h1>Your current weather is: </h1>
<div class="showTemperature">
<p class="showDegree"></p>
</div>
<div class="icon">
</div>
</div>
</body>
这是我的jQuery:
$(document).ready(function(){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=7f5806c8f3fd28b03e2d6580a50732d6", function (data){
var len = data.length;
var location = "";
var temperature = "";
var celsius = Math.floor(data.main.temp - 273.15);
var fahrenheit = Math.floor(9/5 * (data.main.temp - 273) + 32);
function checkSelection(){ if(document.getElementById('celsius').checked) {
//Celsius radio button is checked
return celsius;
}else if(document.getElementById('fahrenheit').checked) {
//Fahrenheit radio button is checked
return fahrenheit;
} else {
return "Please select Fahrenheit or Celsius"
}
};
location += "<p>'" + data.name + ", " + data.sys.country + "'</p>";
temperature += "<p>'" + checkSelection() + "'</p>";
$(".yourLocationGoesHere").html(location);
$(".showDegree").html(temperature);
});
});
请帮忙。
最佳答案
你需要监听 radio 的变化事件,并在事件处理程序的条件下做任何你想做的事情
$(':radio').change(function(){
// "this" will be the checked radio element
if (this.id === 'celsius'){
// code you want for celsius
}else{
// code you want for fahrenheit
}
});
关于javascript - 如何检查选择了哪个单选按钮并在 jQuery 中使用 if else 语句应用适当的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41667149/