这实际上是我第一次使用 jQuery,我已经阅读了教科书中的整章,但发现很难将我的头脑围绕在它上面。我正在尝试将 JavaScript 函数(一个简单的选项选择下拉列表)转换为 jQuery。我尝试了几行从书中或 w3schools 和 api.query 中获得的代码,但无济于事。我会尽量使这个快速而简单,我只是因为某种原因无法理解 jQuery。
我尝试过的通常不起作用。在我的选项列表工作正常之前,我尝试进行试验,但并没有走得太远。
我也为问题的含糊性道歉,我很感激任何帮助!这是我尝试过的东西:
$(document).ready( function () {
var c = ???
if ($(c...
calc.js 和它下面的 index.html
function selectedCountry() {
var c = document.getElementById("countryChooser").value;
var message;
if (c == "nothing") { //if they selected the default option, error pops up.
alert("Please select a country.");
} else if (c == "usa") {
message = "United States of America";
document.getElementById("count").innerHTML = "Your country is: " + message;
} else if (c == "canada") {
message = "Canada";
document.getElementById("count").innerHTML = "Your country is: " + message;
} else {
message = "Mexico";
document.getElementById("count").innerHTML = "Your country is: " + message;
}
}
<script src = "calc.js"></script> <!--JavaSript link -->
<select name="countrylist" id="countryChooser" onchange="selectedCountry()">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
通过jQuery
你可以这样做: -
例子: -
$(document).ready(function(){
$('#countryChooser').change(function(){ // on change of select
if($(this).val()!=='nothing'){ // if selected value is some country
$('#count').html("Your country is: "+$("#countryChooser option:selected").text()); // get country name and add it to paragraph
}else{
$('#count').html("");
alert('Please select a country.'); // alert for selecting a country
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="countrylist" id="countryChooser">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句