我第一次尝试在我的HTML中添加一些JavaScript。
远远没有在这个论坛上提供有用的回复;我有一些我认为很接近但不起作用的东西:
HTML
<select id="carSelect">
<option></option>
<option value="Audi">Audi</option>
<option value="Ferrari">Ferrari</option>
<option value="Fiat">Fiat</option>
</select>
<p id="choiceDisplay">
Selection Display
</p>
JavaScript的:
$('select').change(function(){
const options = $("option");
let selectedOption = "";
let displayString = "";
options.each(function(index){
let option = options[index];
if($(option).prop("selected")) {
selectedOption = $(option).val();
};
if(selecetedOption === "Audi") {
displayString = "Oh I used to have one of those";
};
});
$("#choiceDisplay").empty().append(displayString);
});
我也有jsfiddle link。
答案 0 :(得分:4)
看起来你只是有一个错字:
if (selecetedOption === "Audi") {
无论如何,您可能不需要.each
阻止来获取<select>
的价值:
$("select").change((e) => {
const value = e.target.value || '☝️ Please, select an option';
const displayString = value === "Audi" ? "Audi - Oh I used to have one of those" : value;
$("#choiceDisplay").empty().append(displayString);
});
&#13;
<select id="carSelect">
<option></option>
<option value="Audi">Audi</option>
<option value="Ferrari">Ferrari</option>
<option value="Fiat">Fiat</option>
</select>
<p id="choiceDisplay">☝️ Please, select an option.</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:2)
这个简单的解决方案怎么样?希望它有所帮助!
$("select").change(function(){
let displayString = "";
let selectedOption = $('select[id="carSelect"]');
displayString = (selectedOption.val() === "Audi") ? selectedOption.val() + " Oh I used to have one of those" : selectedOption.val();
$("#choiceDisplay").empty().append(displayString);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="carSelect">
<option></option>
<option value="Audi">Audi</option>
<option value="Ferrari">Ferrari</option>
<option value="Fiat">Fiat</option>
</select>
<p id="choiceDisplay">
Selection Display
</p>
&#13;