从 js 中选择的 html 选项返回最后 2 个字符
Returning last 2 characters from selected html option in js
我有一个 select 盒子,上面附有国家/地区值(例如英国)
我的目标是根据选项 selected
在页面上显示国旗图像
无法在 select 选项中插入图像路径,因此我希望能够提取选项值的最后 2 个字符并在生成的图像 src 中使用它们,例如
<img src="/images/countries/IN.png">
印度
这个可以用js实现吗?
目前我有以下 jQuery returns selected 选项的文本值,但我想在图像 URL 中实现它。
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
document.getElementById("resultDiv").innerHTML = selectedCountry;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form>
<label>Select Country:</label>
<select class="country">
<option value="United States US">United States US</option>
<option value="India IN">India IN</option>
<option value="United Kingdom UK">United Kingdom UK</option>
</select>
</form>
<div id="resultDiv"><img src="images/++RESULT++.png"></div>
您可以使用 .substring() 获取最后两个字符
selectedValue.substring(selectedValue.length-2, selectedValue.length)
我现在已经设法用下面的代码解决了这个问题。感谢大家的帮助!
$(document).ready(function(){
$("select#country").change(function(){
var selectedCountry = $("#country option:selected").val();
var countryCode = selectedCountry.substring(selectedCountry.length-2, selectedCountry.length);
$("#CountryFlag").html("<img src=\"/images/countries/" + countryCode + ".GIF\" /> </object>");
});
});
我有一个 select 盒子,上面附有国家/地区值(例如英国)
我的目标是根据选项 selected
在页面上显示国旗图像无法在 select 选项中插入图像路径,因此我希望能够提取选项值的最后 2 个字符并在生成的图像 src 中使用它们,例如
<img src="/images/countries/IN.png">
印度
这个可以用js实现吗?
目前我有以下 jQuery returns selected 选项的文本值,但我想在图像 URL 中实现它。
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
document.getElementById("resultDiv").innerHTML = selectedCountry;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form>
<label>Select Country:</label>
<select class="country">
<option value="United States US">United States US</option>
<option value="India IN">India IN</option>
<option value="United Kingdom UK">United Kingdom UK</option>
</select>
</form>
<div id="resultDiv"><img src="images/++RESULT++.png"></div>
您可以使用 .substring() 获取最后两个字符
selectedValue.substring(selectedValue.length-2, selectedValue.length)
我现在已经设法用下面的代码解决了这个问题。感谢大家的帮助!
$(document).ready(function(){
$("select#country").change(function(){
var selectedCountry = $("#country option:selected").val();
var countryCode = selectedCountry.substring(selectedCountry.length-2, selectedCountry.length);
$("#CountryFlag").html("<img src=\"/images/countries/" + countryCode + ".GIF\" /> </object>");
});
});